0

Is there a way to spawn randomly in multiple positions for example, I have four SKSpriteNodes which are the locations of where I would like another node to spawn inside of.

These are locations of where I would like the new node to spawn:

//bluesquare
self.bluesquare.position = CGPoint(x:90, y:400)

//greensquare
self.greensquare.position = CGPoint(x:290, y:400)

//yellowsquare
self.yellowsquare.position = CGPoint(x:90, y:150)

//redsquare
self.redsquare.position = CGPoint(x:290, y:150)

When they spawn within the location is there a why to make them spawn in random positions within that SKSpriteNode? (I am using swift with a spritekit game file)

Thanks

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
MattJB
  • 13
  • 6

1 Answers1

2

Use arc4random to create a random number between 0 and 3. Next use if statements to determine your spawn point based on the random number output.

sangony
  • 11,636
  • 4
  • 39
  • 55
  • Thank you! So If number generates as 2, the node will spawn there. But is there a way to spawn randomly inside that location, for example the square nodes (locations of spawn) are 540x700. So when the number generator is called to then spawn randomly within? – MattJB Jun 02 '15 at 11:11
  • 1
    @MattBoulton - I don't understand "spawn randomly inside that location". A CGPoint is a precise location. There's nothing inside a CGPoint. – sangony Jun 02 '15 at 12:45
  • The CGPoint co-ordinates above are for the different squares, so that they are in the correct position on the screen. But, I don't want the new node to spawn on these specific locations but rather inside these square SKSpirteNodes. For example, the bluesquare is positioned on the right of the screen and that covers a quarter of the screen. So how would you spawn an SKSpriteNodes randomly within that square? Thank you – MattJB Jun 02 '15 at 14:14
  • @MattBoulton - Use the arc4random and add whatever value you need. For example, if you need the x value to be between 100 and 150, create a random number between 0 and 50. Then you add 100 to that number to give you your desired number range. – sangony Jun 02 '15 at 14:29
  • Ok Thank you I'll give that a try! – MattJB Jun 02 '15 at 14:35