arc4random function randomly double or triple executing

40 Views Asked by At

I have a function in my code that randomly spawns 1 power every 30-90 seconds. However for some reason the function double or tripple executes every 3-4 executions. Thanks to Ron Myschuk for the help on it to the point it is now, but it's not quite running right at the moment and I hope someone can shed a light on it where in the function I got the mistake.

The functions basically will pick a random interval to wait between 30-90 seconds and then fire one of the power funcs. It then calls itself and re-picks a new interval between 30-90 seconds and picks a new random power up to fire and repeats, and repeats and repeats...

func spawnRandomPowerup() {

    let waitForNextPowerUp = TimeInterval(CGFloat(arc4random() % 5) + 10)
    print("- Next PowerUp spawns in \(waitForNextPowerUp) seconds")

    self.run(.wait(forDuration: waitForNextPowerUp)) {

        let powerup = Int(arc4random_uniform(UInt32(3)))
        print("PowerUp: \(powerup)")

        var spawnPowerUp: SKAction!

        if powerup == 0 {
            spawnPowerUp = SKAction.run(self.spawnALifePowerUp)
            self.run(spawnPowerUp, withKey: "spawningLifePowerUps")
        }
        else if powerup == 1 {
            spawnPowerUp = SKAction.run(self.spawnAShieldPowerUp)
            self.run(spawnPowerUp, withKey: "spawningShieldPowerUps")
        }
        else if powerup == 2 {
            spawnPowerUp = SKAction.run(self.spawnARapidFirePowerUp)
            self.run(spawnPowerUp, withKey: "spawningRapidFirePowerUps")
        }

        self.spawnRandomPowerup()
    }
}

I tired a few things like starting the function with self.removeAllActions() but that only made things worst. Thanks in advance for having a look at this.

1

There are 1 best solutions below

0
AudioBubble On

I posted the spawnRandomPowerup() call in the startNewLevel function instead of the startGame function, which caused the spawnRandomPowerup() call to fire every time a 100 points were reached.

Thanks again to Ron for helping me find this one. Learning a lot from this guy!