触摸在游戏中的实现

Touch implementation in game

我正在使用 Swift 3 和 Xcode 8,我正在尝试使用 SpritKit 制作简单的游戏。基本上我想要做的是允许玩家只左右移动我的精灵(在屏幕上拖动它)并在实现手指(触摸结束)后对精灵应用冲动。我已经设法做到了,但我希望它只在第一次触摸时发生,所以在对 sprite 玩家施加冲动后,玩家不能再与 sprite 交互,直到发生一些碰撞或类似情况。下面是我的代码,它不仅在第一次触摸时一直有效。

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))
        }
    }
}

正如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
}