我正在制作一个游戏,我在屏幕上移动精灵,但如果我点击屏幕它会移动到那个位置,我只想让它移动,如果我把手指放在屏幕上,这样精灵将跟随我的手指它不会通过我的物体传送
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchLocation = touch.location(in: self)
player.position.x = touchLocation.x
}
}
我试过这个(玩家是我的精灵)并且它有效,当我移动我的手指精灵将跟随,但如果我点击屏幕一侧的fx它会传送到那个位置而我不希望这发生。
请尝试以下代码:
var isDragging = false
var player = /* SKSpriteNode or whatever */
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let touchLocation = touch.location(in: view)
if player.contains(touchLocation) {
isDragging = true
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isDragging else { return }
if let touch = touches.first {
let touchLocation = touch.location(in: view)
player.position.x = touchLocation.x
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isDragging = false
}
touchesBegan - 通过使用contains()
确保触摸位置在播放器内的某个位置。
touchesMoved - 如果正在拖动玩家,请将玩家移动到触摸的位置。
touchesEnded - 触摸结束后,拖动将停止。