2016-09-28 76 views
2

在我的遊戲中,我使用SKActions按順序將一個節點(在這種情況下爲槳)移動到某個位置並返回,這部分工作正常。每當用戶在屏幕上觸摸它時,槳就會移動。我此代碼如下:Swift - 在節點被觸摸之後,直到它再次被觸摸爲止

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    let touch = touches.first! 
    let touchLocation = touch.location(in: self) 
    let nodeTouched:SKPhysicsBody? = self.physicsWorld.body(at: touchLocation) 
    let ballNode = self.childNode(withName: ballName) 

    if nodeTouched?.node?.name == RpaddleName { 

     if !paddleRTouched { 
      paddleRTouched = true 
      let Rpaddle = self.childNode(withName: RpaddleName) as! SKSpriteNode 
      let startPosition = CGPoint(x: 301.7, y: 87) 
      let newPosition = CGPoint(x: 226.7, y: 87) 
      let moveToNew = SKAction.move(to: newPosition, duration: 0.5) 
      let moveToOld = SKAction.move(to: startPosition, duration: 0.5) 
      let delay = SKAction.wait(forDuration: 0.5) 
      let sequence = SKAction.sequence([moveToNew,delay,moveToOld]) 
      Rpaddle.run(sequence) 
      paddleRTouched = false 

但是我需要創建期間,如果它toucher(例如停用一段時間)的槳不能移動5秒延遲。我怎麼能這樣做?

回答

0

刪除他上面代碼的最後一行:

paddleRTouched = false 

......與此類似的東西取代它:

let allowPaddleTouchAction = SKAction.run { 
     self.paddleRTouched = false 
    } 
    let allowTouchDelay = SKAction.wait(forDuration: 5) 
    run(SKAction.sequence([allowTouchDelay, allowPaddleTouchAction])) 
+0

感謝完美地工作 –

1

我想給的替代好T. Benjamin Larsen answer's可能在類似於你經常情況下非常有用,您可以使用SKTUtilslibrarySKAction擴展:

public extension SKAction { 
    /** 
    * Performs an action after the specified delay. 
    */ 
    public class func afterDelay(_ delay: TimeInterval, performAction action: SKAction) -> SKAction { 
     return SKAction.sequence([SKAction.wait(forDuration: delay), action]) 
    } 

    /** 
    * Performs a block after the specified delay. 
    */ 
    public class func afterDelay(_ delay: TimeInterval, runBlock block: @escaping() -> Void) -> SKAction { 
     return SKAction.afterDelay(delay, performAction: SKAction.run(block)) 
    } 
} 

所以,當你需要一定的延遲後執行的操作,你可以直接做:

run(SKAction.afterDelay(5, runBlock: { 
    self.paddleRTouched = false 
}))