2016-10-22 119 views
0

我在Xcode 8上使用Swift 3,我試圖用SpritKit製作簡單的遊戲。基本上我想要做的是讓玩家將我的精靈左右移動(將其拖動到屏幕上),然後在實現手指(觸摸結束)後在精靈上應用衝動。我設法做到了這一點,但我希望僅在第一次觸摸時纔會發生,所以在Sprite上應用衝動後,不能再與Sprite進行交互,直到發生碰撞或simillar。下面是我的代碼,它不僅在第一次觸摸時一直有效。在遊戲中觸摸實施

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



} 

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for t in touches { 

     let location = t.location(in: self) 

     if player.contains(location) 
     { 
      player.position.x = location.x 
     } 
    } 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for t in touches { 

     if let t = touches.first { 

      player.physicsBody?.isDynamic = true 
      player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50)) 
     } 
    } 
} 
+0

你唯一需要的是一個布爾變量,無論是在現場還是在一些自定義類,它將跟蹤是否允許交互。因此,在應用衝動後,將布爾值設置爲false,然後在didBegin(contact :)中相應地更改該布爾值。 – Whirlwind

+0

我可以添加變量脈衝設置爲默認值,並且只有當變量脈衝> 0時,才允許用戶與精靈進行交互。將脈衝設置爲零之後,直到開始接觸發生 –

+0

只需使用true和false即可。我的意思是1和0會工作,但沒有必要。或者,也許你可以使用一些physicsBody的屬性來確定是否允許交互。這取決於你的遊戲如何運作,以及最適合你的遊戲。但底線是,這是一項簡單的任務,可以通過多種方式完成。 – Whirlwind

回答

1

由於Whirlwind評論,你只需要一個布爾值來確定時,你應該控制對象:

/// Indicates when the object can be moved by touch 
var canInteract = true 

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

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for t in touches { 
     let location = t.location(in: self) 
     if player.contains(location) && canInteract 
     { 
      player.position.x = location.x 
     } 
    } 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for t in touches { 

     if let t = touches.first && canInteract { 
      canInteract = false //Now we cant't interact anymore. 
      player.physicsBody?.isDynamic = true 
      player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50)) 
     } 
    } 
} 
/* Call this when you want to be able to control it again, on didBeginContact 
    after some collision, etc... */ 
func activateInteractivity(){ 
    canInteract = true 
    // Set anything else you want, like position and physicsBody properties 
}