SpriteKit 如何在每次不同随机数的动画循环后重复 SKAction?

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

我有一个带有纹理动画的 SKSpriteNode。我基本上有一个 4 帧的角色空闲周期和一个闪烁动画序列。我想永远循环角色空闲循环,但让它以随机间隔播放闪烁动画序列。

我有以下代码;

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)

    runAction(repeatSequence)

}

func randomLoopCount() -> Int {

    return Int(arc4random_uniform(10) + 2)

}

上面的问题是,随机数只生成一次,所以眨眼根本不会随机发生。每次都在相同数量的循环之后。如何达到我想要的效果?

你可以使用递归来实现你想要的:

func playIdle() {

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

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

        runAction(sequence)

    }

部分unowned self protects you from creating a strong reference cycle.