Geoff H Geoff H - 10 days ago 6x
iOS Question

SpriteKit how to repeat an SKAction after a VARYING random number of animation loops each time?

I have an SKSpriteNode with texture animations. I basically have a character idle cycle of 4 frames and a blink animation sequence. I want to loop the character idle cycle forever but make it play the blink animation sequence at random intervals.

I have the following code;

func playIdle() {

let idle_loop = SKAction.repeatAction(action_textureSequence_idle!, count: randomLoopCount())

let sequence = SKAction.sequence([idle_loop, action_textureSequence_blink!])

let repeatSequence = SKAction.repeatActionForever(sequence)



func randomLoopCount() -> Int {

return Int(arc4random_uniform(10) + 2)


The problem with the obove is, the random number is only generated once so the blink does not happen randomly at all. Just after the same number of loops each time. How do I achieve the effect I'm looking for?


You can use recursion to achieve what you want:

func playIdle() {

        let idle_loop = SKAction.repeatAction(action_textureSequence_idle, count: Int(arc4random_uniform(10) + 2))

        let sequence = SKAction.sequence([idle_loop,
                                            SKAction.runBlock({[unowned self] in self.playIdle()})])



The part unowned self protects you from creating a strong reference cycle.