SpriteKit 动画

ACo*_*lio 4 animation sprite-kit swift

我有这段代码,它可以在我按住我创建的按钮的整个过程中执行我想要执行的动画。不过,我希望在按住按钮时重复此操作。一旦我放开它,精灵就会回到站立位置。

func runForward()
{
    let run = SKAction.animateWithTextures([
        SKTexture(imageNamed: "walk1"),
        SKTexture(imageNamed: "walk2"),
        SKTexture(imageNamed: "walk3"),
        SKTexture(imageNamed: "walk4")
    ], timePerFrame: 0.09)
    
    _hero!.runAction(run)
}
Run Code Online (Sandbox Code Playgroud)

如果我将此代码放入更新中,它会更新每一帧,导致动画只有在我将手指从按钮上移开后才能完成。如果我在单击按钮后启动此动画,它只会在开始时执行它。我想知道如何让它连续运行,直到我将手指从按钮上移开。

这是按钮的代码,它只是放置在屏幕上的 Sprite 节点。

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
}
Run Code Online (Sandbox Code Playgroud)

dux*_*x-- 6

您想要做的是在触摸开始时启动动画 ( touchesBegan),并在触摸结束时结束动画 ( touchesEnded)。

因此,一旦触摸开始,您应该执行永远重复的操作。该操作将有一个键(或名称)。一旦触摸结束,您可以使用按键(或名称)取消永久运行的操作(因此它将停止动画)

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")
   }
}
Run Code Online (Sandbox Code Playgroud)