【问题标题】:how to move the sprite when touch the screen and disable when I tap the screen如何在触摸屏幕时移动精灵并在我点击屏幕时禁用
【发布时间】:2019-04-18 20:40:21
【问题描述】:

我正在制作一个游戏,我在屏幕上移动一个精灵,但如果我点击屏幕,它会移动到那个位置,我只希望它在我将手指放在屏幕上时移动,这样精灵就会跟随我的手指,它不会通过我的物体传送

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,它会传送到那个位置而我没有希望发生这种情况。

【问题讨论】:

  • 你想让它动画到新的位置吗?或者根本没有移动,因为它最初没有被按下来拖动?
  • 如果我只是在屏幕上按下它不应该移动到那个位置,但是如果我在屏幕上拖动我的手指它应该跟随,但我不知道该怎么做。跨度>

标签: swift xcode skspritenode touchesmoved


【解决方案1】:

试试下面的代码:

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 - 当触摸结束时,拖动将停止。

【讨论】:

  • @frederikNiebling 很高兴听到!
猜你喜欢
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
相关资源
最近更新 更多