我是Swift和SpriteKit的新手。很多SpriteKit动作的样本都在Objective C中,我可以在Swift中映射,也不会工作。
如果运行SKAction,并且在SKAction完成后想要做其他事情,我如何在Swift中做到这一点?
spaceMan.runAction(spaceManDeathAnimation, completion: {
println("red box has faded out")
})
任何想法都将不胜感激。
编辑:
for i in 0...29 {
textures.append(SKTexture(imageNamed: "spaceManDeath_\(i)"))
}
spaceManDeathAnimation = SKAction.repeatActionForever(SKAction.animateWithTextures(textures, timePerFrame: 0.15625))
答案 0 :(得分:4)
在这里发现了一个问题:
spaceManDeathAnimation = SKAction.repeatAction(SKAction.animateWithTextures(textures, timePerFrame: 0.15625), count: 1)
此外,正如sangony发布了一个非常好的链接 - 解决了完成块语法
spaceMan.runAction(spaceManDeathAnimation, completion: {() -> Void in
println("death")
})
非常感谢大家为解决方案做出的贡献!
答案 1 :(得分:4)
由于您的“死亡”操作永远在运行,因此您的完成代码未被调用,这意味着它永远不会结束。
您可以使用
+ repeatAction:count:
设置完成前将进行多少次重复计数的方法:
spaceManDeathAnimation = SKAction.repeatAction(SKAction.animateWithTextures(textures, timePerFrame: 0.15625), count:5)
答案 2 :(得分:3)
在Swift中你可以使用这个扩展名:
extension SKNode
{
func runAction( action: SKAction!, withKey: String!, optionalCompletion: dispatch_block_t? )
{
if let completion = optionalCompletion
{
let completionAction = SKAction.runBlock( completion )
let compositeAction = SKAction.sequence([ action, completionAction ])
runAction( compositeAction, withKey: withKey )
}
else
{
runAction( action, withKey: withKey )
}
}
}
例如用作:
myShip.runAction(move,withKey:"swipeMove",optionalCompletion: {
//Here action is ended..do whatever you want
}
extension SKNode
{
func run(action: SKAction!, withKey: String!, optionalCompletion:((Void) -> Void)?) {
if let completion = optionalCompletion
{
let completionAction = SKAction.run(completion)
let compositeAction = SKAction.sequence([ action, completionAction ])
run(compositeAction, withKey: withKey )
}
else
{
run( action, withKey: withKey )
}
}
func actionForKeyIsRunning(key: String) -> Bool {
return self.action(forKey: key) != nil ? true : false
}
}
<强>用法强>:
myShip.runAction(action: move, withKey:"swipeMove", optionalCompletion: {
//Here action is ended..do whatever you want
}