11

我是 Swift 和 SpriteKit 的新手。SpriteKit Actions 的许多示例都在 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))
4

3 回答 3

5

在这里发现一个问题:

spaceManDeathAnimation = SKAction.repeatAction(SKAction.animateWithTextures(textures, timePerFrame: 0.15625), count: 1)

此外,正如 sangony 发布了一个非常好的链接 - 解决了完成块语法

    spaceMan.runAction(spaceManDeathAnimation, completion: {() -> Void in
        println("death")
    })

非常感谢大家为解决方案做出的贡献!

于 2015-04-14T13:03:22.897 回答
4

您的完成代码不会被调用,因为您的“死亡”操作将永远运行,这意味着它永远不会结束。

您可以使用

+ repeatAction:count:

在完成之前设置重复次数的方法:

spaceManDeathAnimation = SKAction.repeatAction(SKAction.animateWithTextures(textures, timePerFrame: 0.15625), count:5)
于 2015-04-14T13:03:40.810 回答
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
}

斯威夫特 3:

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
}
于 2016-06-09T10:07:20.480 回答