2016-10-22 95 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 
}