You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpriteKit中touchesMoved触发节点跳转至触摸位置的解决方法咨询

解决Player在touchesMoved中瞬移的问题

这个问题很常见——你当前的代码是直接将player的位置硬赋值为触摸的当前坐标,这就导致不管触摸从哪里移动到哪里,player都会瞬间跳到目标点,完全没有平滑的跟随效果。要修复这个问题,我们需要计算触摸的移动增量,用增量来更新player的位置,而不是直接覆盖它的坐标。

具体实现步骤:

  1. 首先在你的场景类中添加一个属性,用来记录上一次触摸的位置:
private var lastTouchLocation: CGPoint?
  1. 在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)
}
  1. 修改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
}
  1. 最后在touchesEnded方法中重置记录的触摸位置,避免下一次触摸时出现异常:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    lastTouchLocation = nil
}

原理说明:

这样修改后,player会跟随触摸的每一次微小移动逐步平移,而不是瞬间跳到触摸的当前位置。核心是通过记录上一次触摸的位置,计算两次触摸之间的差值,再把这个差值加到player的位置上,实现平滑的跟随效果。

内容的提问来源于stack exchange,提问作者Dbxsk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:02:55