SKAction Completion Handlers; usage in Swift

前端 未结 3 1132
情书的邮戳
情书的邮戳 2020-12-17 18:27

I\'m new to Swift and SpriteKit. A lot of the samples of SpriteKit Actions are in Objective C, which I can\'t map to, nor get working, in Swift.

If running an SKAct

相关标签:
3条回答
  • 2020-12-17 19:11

    You completion code is not called since your "death" action is running forever, which means it will never end.

    You can use

    + repeatAction:count:
    

    method for setting a count for how many repeats will be made before finishing:

    spaceManDeathAnimation = SKAction.repeatAction(SKAction.animateWithTextures(textures, timePerFrame: 0.15625), count:5)
    
    0 讨论(0)
  • 2020-12-17 19:14

    In Swift you can use this extension:

    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 )
            }
        }
    }
    

    Use for example as:

    myShip.runAction(move,withKey:"swipeMove",optionalCompletion: {
      //Here action is ended..do whatever you want
    }
    

    Swift 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
        }
    }
    

    Usage:

    myShip.runAction(action: move, withKey:"swipeMove", optionalCompletion: {
           //Here action is ended..do whatever you want
    }
    
    0 讨论(0)
  • 2020-12-17 19:15

    Found an issue here:

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

    Also,as sangony posted a very nice link - solved the completion block syntax to

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

    Very big thanks to everybody for contributions for a solution!

    0 讨论(0)
提交回复
热议问题