触摸游戏

时间:2016-10-22 18:37:42

标签: sprite-kit swift3 game-physics xcode8 touches

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

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

1 个答案:

答案 0 :(得分: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
}