Create SKSpriteNode between two positions arbitrarily
I am trying to figure out how to call SKSpriteNode
between two positions (positioned on the screen) randomly in Swift.
This is what I ran into, but it spawns out-of-screen nodes even though I defined two points inside the borders of the screen!
/* 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))
source to share
You just need to add your random value to MinSpawnValue
. The types may require some customization:
Node.position = CGPointMake(CGFloat(arc4random_uniform(SpawnPosition)) + MinSpawnValue,CGRectGetMidY(self.frame))
I find it easier to think about things like this using actual numbers. For example, if there MinSpawnValue
were 1000
and MaxSpawnValue
were 1004
, then there SpawnPosition
will be 4
, and you should generate a number in the range 0...3
. By adding this number to MinSpawnValue
, you get a number in the range 1000...1003
.
source to share