您可以使用 SKAction 序列,它是 waitForDuration:withRange: 方法,如下所示:
//By default, the sprite is initialized with downTexture
let sprite = SKSpriteNode(texture: downTexture)
sprite.position = CGPoint(x: 200, y: 200)
addChild(sprite)
let sequence = SKAction.sequence([
SKAction.runBlock({NSLog("Up texture set")}), //Added just for debugging to print a current time
SKAction.setTexture(upTexture),
SKAction.waitForDuration(2.5, withRange: 3.0), //Wait between 1.0 and 4.0 seconds
SKAction.runBlock({NSLog("Down texture set")}),
SKAction.setTexture(downTexture),
SKAction.waitForDuration(0.65, withRange: 0.7),//Wait between 0.3 and 1.0 seconds
])
let action = SKAction.repeatActionForever(sequence)
sprite.runAction(action, withKey: "aKey")
这段代码的作用是创建一个精灵,默认使用 downTexture 对其进行初始化,然后:
- 立即将纹理交换为 upTexture
- 等待 1 到 4 秒
- 将纹理交换为 downTexture
- 等待 0.3 到 1 秒
- 永远重复这一切
如果你想停止这个动作,你可以像这样访问它:
if sprite.actionForKey("aKey") != nil {
removeActionForKey("aKey")
}