Vince Vince - 6 months ago 4
Swift Question

How do I get a SKAction to repeat itself after a random period of time

I currently have the below code that happily repeats an action every 2 seconds, but I want it to happen at a completely random period of time, e.g sometime between 1 and 10 seconds, I tried a few different lines of code using arch4random of which none worked. I'm hoping its a simple fix, any advice is greatly appreciated.


runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(callBird), SKAction.waitForDuration(2.0)])))


If you are trying to randomize a duration parameter, a + waitForDuration:withRange: will do the job.

                SKAction.sequence([SKAction.runBlock({/*do your stuff*/}),
                   SKAction.waitForDuration(2, withRange: 3) ])))

From the docs :

Each time the action is executed, the action computes a new random value for the duration. The duration may vary in either direction by up to half of the value of the durationRange parameter.

Means that if a duration is set to 2 and a range parameter is set to 3, a possible duration value will vary between 0.5 and 3.5.