2015-04-19 75 views
1

我有这段代码可以在我按住我创建的按钮的整个过程中执行动画。不过,我希望在按钮被按住时重复此操作。一旦我放弃了它,它会将精灵恢复到站立的位置。 func runForward() { let run = SKAction.animateWithTextures([ SKTexture(imageNamed: "walk1"), SKTexture(imageNamed: "walk2"), SKTexture(imageNamed: "walk3"), SKTexture(imageNamed: "walk4") ], timePerFrame: 0.09) _hero!.runAction(run) } 如果我将此代码放入更新中,它会更新每一帧,导致动画只有在我将手指从按钮上抬起时才会完成。如果我点击按钮启动这个动画,它只会在开始时执行它。我想知道如何让它连续运行,直到我将手指从按钮上移开。SpriteKit动画

继承人只是在屏幕上放置一个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 }

+0

请添加合适的代码高亮显示,这实际上是不可读。 – Alexander

+0

对不起,我意识到,我发布后,但只是把它设置为一个更好的格式 – AConsiglio

回答

4

你想要做的是启动动画,当你触摸开始(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") 
    } 
} 
+0

感谢人的工作就像一个魅力! – AConsiglio

+0

没有probs,upvote并接受答案会很好:) –