Swift Sprite-kit:如何设置随机时间的动画?

时间:2015-01-10 07:33:25

标签: ios animation swift sprite-kit skaction

    var lightTexture = SKTexture(imageNamed: "green light.png")
    var lightTexture2 = SKTexture(imageNamed: "red light.png")

    var animationLight = SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame:     3)
    var changeLight = SKAction.repeatActionForever(animationLight)

    light = SKSpriteNode(texture: lightTexture)
    light.position = CGPointMake(CGRectGetMidX(self.frame), 650)
    light.runAction(changeLight)

    self.addChild(light)

我想让动画以随机时间间隔(1秒到3秒之间的随机时间)设置。然后,如果在红灯亮起时触摸屏幕,我想要出现一个游戏符号。提前谢谢。

1 个答案:

答案 0 :(得分:4)

您需要使用的是SKAction.waitForDuration(_:withRange :)

https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKAction_Ref/index.html#//apple_ref/occ/clm/SKAction/waitForDuration:withRange

或更具体地说:

let lightTexture = SKTexture(imageNamed: "green light.png")
let lightTexture2 = SKTexture(imageNamed: "red light.png")

let animateLights = SKAction.sequence([
    SKAction.waitForDuration(2.0, withRange: 2.0),
    SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)
    ])

let changeLight = SKAction.repeatActionForever(animateLights)

let light = SKSpriteNode(texture: lightTexture)
light.position = CGPointMake(400, 650)
light.runAction(changeLight)

self.addChild(light)

根据文档,您的动画将持续2秒+/- 1秒。

另请注意,我冒昧地将“var”变量更改为“let”常量,因为它们没有被更改。