3

I am trying to work out how to spawn a SKSpriteNode between two positions (located on the screen) randomly in Swift.

This is what I came up with, but it does spawn Nodes outside the screen dimensions altough I defined two points inside the screen bounds!

/* Spawning Values */
var MinSpawnValue = self.size.width / 8
var MaxSpawnValue = self.size.width - self.size.width / 8
var SpawnPosition = UInt32(MaxSpawnValue - MinSpawnValue)
/* Node Positioning */
Node.position = CGPointMake(CGFloat(arc4random_uniform(SpawnPosition)),CGRectGetMidY(self.frame))
vacawama
  • 150,663
  • 30
  • 266
  • 294
Devapploper
  • 6,062
  • 3
  • 20
  • 41
  • 1
    Variable names really should start with lowercase letters. Notice that the syntax highlighting above is confused and showing your variable names as blue because it thinks that they are class names. – vacawama Aug 02 '15 at 12:06

1 Answers1

2

You just need to add your random value to MinSpawnValue. This may need some adjusting for types:

Node.position = CGPointMake(CGFloat(arc4random_uniform(SpawnPosition)) + MinSpawnValue,CGRectGetMidY(self.frame))

I find it easier to think about things like this by using actual numbers. For instance, if MinSpawnValue were 1000 and MaxSpawnValue were 1004, then SpawnPosition would be 4 and you would generate a number in the range 0...3. By adding that number to MinSpawnValue, you'd get a number in the range 1000...1003.

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Thank you! Great answer and so fast! – Devapploper Aug 02 '15 at 12:12
  • You're welcome! Your question is an example of a perfectly asked question on Stack Overflow. It stated what was happening, what you wanted to happen, included the relevant code which showed effort, had relevant tags, and a clearly stated title. That is how it is done! If only more questions were as clearly stated as yours. – vacawama Aug 02 '15 at 12:34