1
votes

I have this code that does the animation that I want to be executed over the entire time I'm holding down a button that I've created. However I would like this to repeat while the button is being held. Once I've let go it would return the sprite back to a standing position. func runForward() { let run = SKAction.animateWithTextures([ SKTexture(imageNamed: "walk1"), SKTexture(imageNamed: "walk2"), SKTexture(imageNamed: "walk3"), SKTexture(imageNamed: "walk4") ], timePerFrame: 0.09) _hero!.runAction(run) } If I put this code inside of update it updates every frame causing the animation to only finish once I lift my finger off the button. If I start this animation once the button is clicked it only performs it at the very beginning. I was wondering how I get this to run consecutively until I lift my finger off the button.

Heres the code of the button which is just a Sprite Node placed on screen. override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */
// Loop over all the touches in this event for touch: AnyObject in touches { // Get the location of the touch in this scene let location = touch.locationInNode(self) // Check if the location of the touch is within the button's
if (right.containsPoint(location)) { _right = true runForward() } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { _right = false }

1
Please add proper code highlighting, this is practically unreadable. - Alexander
Sorry I realized that after I posted it but just got it set into a better format - AConsiglio

1 Answers

4
votes

What you want to do is start the animation when your touch begins (touchesBegan) and end the animation when your touch ends (touchesEnded).

Therefore, you should perform an action that repeats forever once your touch begins. This action will have a key (or a name). Once your touch ends, you can use the key (or name) to cancel the action that is running forever (thus it will stop the animation)

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let run = SKAction.animateWithTextures([
            SKTexture(imageNamed: "walk1"),
            SKTexture(imageNamed: "walk2"),
            SKTexture(imageNamed: "walk3"),
            SKTexture(imageNamed: "walk4")
            ], timePerFrame: 0.09)
        hero.runAction(SKAction.repeatActionForever(SKAction.sequence([
                        run,
                        SKAction.waitForDuration(0.001)
                        ])
                        ), withKey: "heroRunning"
                    )
    }
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
   for touch: AnyObject in touches {
      hero.removeActionForKey("heroRunning")
   }
}