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

Unity中如何存储物体上一帧位置?缓存位置值始终相同排查

Unity脚本问题修复:lastPosition与currentPosition始终相同的原因

核心错误

你的代码中lastPosition的赋值逻辑完全颠倒,导致每帧位置差值始终为0:

  • 每帧开始时,你将当前物体位置存入currentPosition
  • 执行移动逻辑修改位置后,你把移动后的新位置赋值给lastPosition
  • 下一帧读取currentPosition时,它就是上一帧最后设置的新位置,和lastPosition完全一致,进而导致currentSpeed计算为0,strengthMultiplier也为0,移动逻辑彻底失效,位置不再变化

修复代码

将Update方法末尾的lastPosition赋值改为移动前的currentPosition,确保它存储的是上一帧的最终位置:

// 执行移动逻辑
transform.position += moveDir * moveSpeed * strengthMultiplier * Time.deltaTime;

// 存储当前帧移动前的位置,作为下一帧的"上一帧位置"
lastPosition = currentPosition;

额外优化

初始帧currentSpeed为0会导致第一次移动无响应,建议给strengthMultiplier添加最小阈值:

// 替换原strengthMultiplier计算行
strengthMultiplier = Mathf.Max(currentSpeed / strengthDiminisher, 0.1f);

另外,isRollingBackwards、isRollingLeft、isRollingRight的判断依赖transform.rotation的分量,这并不准确(四元数分量范围和欧拉角逻辑不同),建议改用速度方向或欧拉角的Y轴旋转来判断移动方向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:53:12