blue
blue

Reputation: 7385

Swift: spawn enemies at random times within a range?

Alright so I know this question has been answered for those asking in several other languages but it doesn't seem as though anyone has asked for Swift yet.

I'm creating a sprite kit game and I need to spawn my enemies at random times (within a 0-2 sec range). Right now I have them spawning every second using delays. Here is the enemy spawn func:

func spawnEnemy1() {
        var enemy1Texture = SKTexture(imageNamed: "enemy1")

        enemy1 = SKSpriteNode(texture: enemy1Texture)
        enemy1.setScale(0.3)
        enemy1.name = "enemy1"

        enemy1.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 1.2)
        enemy1.zPosition = 55

        var enemyPhysicsSize = CGSize(width: enemy1.size.width,height: 65)
        enemy1.physicsBody = SKPhysicsBody(rectangleOfSize: enemyPhysicsSize)
        enemy1.physicsBody?.dynamic = false

        enemy1.physicsBody?.categoryBitMask = ColliderType.Enemy1.rawValue
        enemy1.physicsBody?.contactTestBitMask = ColliderType.Savior.rawValue
        enemy1.physicsBody?.collisionBitMask = ColliderType.Savior.rawValue

        self.addChild(enemy1)

        let enemyMoveDown = SKAction.moveTo(CGPointMake(self.size.width * 0.5,-100), duration:5.6)

        let scaleEnemy = SKAction.scaleTo(0.5, duration: 5.6)

        let enemyScaleDown = SKAction.group([enemyMoveDown, scaleEnemy])

        enemy1.runAction(enemyScaleDown)
    }

Here is executing the spawn func:

let enemy1SpawnDelay = SKAction.waitForDuration(1)

        runAction(SKAction.repeatActionForever(
            SKAction.sequence([
                enemy1SpawnDelay,
                SKAction.runBlock({self.spawnEnemy1()}),
                SKAction.waitForDuration(5.6)])))

(I don't want multiple enemies on the screen at once and it takes 5.6 sec for the enemy to move down the screen, hence the last delay).

The enemy1SpawnDelay controls the amount of time that can pass between when the last enemy appeared and when the next will appear, so I need to know how I can make enemy1SpawnDelay be set equal to a new random number between 0-2 each time an enemy is spawned.

How can I do this? Or is there a better way to accomplish this?

Upvotes: 0

Views: 1426

Answers (1)

Wraithseeker
Wraithseeker

Reputation: 1904

Make use of arc4random which returns a random value between 0 to your number

spawndelay = arc4random_uniform(UInt32(yournumber))

For Double from here

func random(#lower: Double, upper: Double) -> Double {
    let r = Double(arc4random(UInt64)) / Double(UInt64.max)
    return (r * (upper - lower)) + lower
}

Upvotes: 0

Related Questions