Calling a function indefinitely at random intervals

Viewed 196

Making a Swift game. Trying to activate the function "fireFrisbee" at random time intervals between 0-3 seconds forever.

iphone simulation shows a white screen. The function only seems activate once (only one frisbee firing sound heard)

let action = SKAction.sequence([SKAction.run(fireFrisbee), SKAction.wait(forDuration: TimeInterval(arc4random_uniform(3)))])

run(SKAction.repeatForever(action))

I have this line of code under override func didMove(to view: SKView) {

1 Answers

a couple things to note, if that code worked you could run into some issues where a Frisbee is set to fire at 3 seconds and then it runs the action again and the next could fire at 0 seconds (doubling up the actions) and potentially the next action could fire at 0 seconds (tripling up the action) kinda a mess.

But that code won't work anyway, what is happening is that you are getting a random value TimeInterval(arc4random_uniform(3)) but you are essentially hard coding that action with that random value. when the action repeats it will always have that hard coded random value in it. so if the first time you run it and it generates a random 2 it will always run every 2 seconds.

there are a couple of ways you could do this you could put a random generator inside your update func to call fireFrisbee. Or you could create a recursive action with a completion call that would fire itself when it is done completing....

let wait = SKAction.wait(forDuration: 5)
run(wait) {
    self.setupFireFrisbee() 
}

func setupFireFrisbee() {
    action = SKAction.sequence([SKAction.run(fireFrisbee), SKAction.wait(forDuration: TimeInterval(arc4random_uniform(3)))])
    //completion shortcut {} after action
    run(action) {
        self.setupFireFrisbee() 
    }
}
Related