2015-04-19 105 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並接受答案會很好:) –