2016-10-22 5 views
0

私はXcode 8でSwift 3を使用しています。私はSpritKitで簡単なゲームを作ろうとしています。基本的に私がしようとしているのは、スプライトを左右に動かすだけです(画面上でドラッグします)。私はそれを行うことができましたが、私はそれが最初のタッチでのみ起こるように、スプライトプレイヤーにインパルスを加えた後、スプライトと何かコリソンが起こるかsimilararまではもう対話できません。以下は、最初のタッチだけでなく、常に動作する私のコードです。ゲームのタッチ実装

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

真と偽を使用してください。私は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 
} 
関連する問題