Search code examples
iosswiftsprite-kitarc4random

Setting limits to sprite vertical location with arc4Random


I'm building my first 2D platform game and I'm looking to set some limits to objects that are generated every few seconds using arc4Random.

Currently a bird will fly across the screen from right to left and most of the time the bird appears to be in the air, however sometimes the bird it at ground level that just looks strange.

What I would like to do is to set a minimum and maximum height the birds will be generated in, is this possible?

Here is some of the code...

func spawnBird() {
    var birdP = SKNode()
    birdP.position = CGPointMake( self.frame.size.width + birdTexture1.size().width * 2, 0 );
    birdP.zPosition = -10;
    var height = UInt32( self.frame.size.height / 1 )
    var y = arc4random() % height;
    var bird1 = SKSpriteNode(texture: birdTexture1)
    //Code Removed

birds.addChild(birdP)

Solution

  • You could set a minimum and maximum height:

    var height_max = UInt32( self.frame.size.height )
    var height_min = UInt32( 20 )
    var bird_range = arc4random_uniform(height_max - height_min + 1) + height_min;
    

    Alternate method:

    var bird_range = (arc4random() % (height_max - height_min) + 1) + height_min;
    

    Methods Graphed:

    enter image description here

    The two using max/min height never got below 20, the original method you're using often hit 0.