SpriteKit中touchesMoved触发节点跳转至触摸位置的解决方法咨询
解决Player在touchesMoved中瞬移的问题
这个问题很常见——你当前的代码是直接将player的位置硬赋值为触摸的当前坐标,这就导致不管触摸从哪里移动到哪里,player都会瞬间跳到目标点,完全没有平滑的跟随效果。要修复这个问题,我们需要计算触摸的移动增量,用增量来更新player的位置,而不是直接覆盖它的坐标。
具体实现步骤:
- 首先在你的场景类中添加一个属性,用来记录上一次触摸的位置:
private var lastTouchLocation: CGPoint?
- 在
touchesBegan方法中,记录第一次触摸的初始位置:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let touch = touches.first else { return } lastTouchLocation = touch.location(in: self) }
- 修改
touchesMoved方法,通过计算触摸位置的偏移量来更新player的位置:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) guard let touch = touches.first, let lastLocation = lastTouchLocation else { return } let currentLocation = touch.location(in: self) // 计算触摸移动的X、Y方向偏移量 let deltaX = currentLocation.x - lastLocation.x let deltaY = currentLocation.y - lastLocation.y // 用偏移量逐步更新player的位置,而不是直接赋值 player.position.x += deltaX player.position.y += deltaY // 更新上一次触摸位置,为下一次移动计算做准备 lastTouchLocation = currentLocation }
- 最后在
touchesEnded方法中重置记录的触摸位置,避免下一次触摸时出现异常:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) lastTouchLocation = nil }
原理说明:
这样修改后,player会跟随触摸的每一次微小移动逐步平移,而不是瞬间跳到触摸的当前位置。核心是通过记录上一次触摸的位置,计算两次触摸之间的差值,再把这个差值加到player的位置上,实现平滑的跟随效果。
内容的提问来源于stack exchange,提问作者Dbxsk
相关产品推荐
相关产品推荐

