Unity中Rigidbody第三人称角色左右移动抖动问题求助
问题分析与解决方案
你的左右移动抖动问题源于代码拼写错误、物理移动逻辑不合理,以及输入处理的疏漏,以下是具体修正方案:
1. 修复笔误
代码中Quaternion.Eulee是拼写错误,正确写法为Quaternion.Euler——这个错误会直接导致左右移动时的方向计算异常,引发抖动。
2. 优化Rigidbody移动逻辑
直接覆盖rb.velocity会干扰物理引擎的平滑计算,改用速度插值的方式调整刚体速度;同时原代码中100f的倍率过高,结合Time.fixedDeltaTime会导致速度突变,需要移除冗余倍率并保留Y轴物理效果(比如重力)。
3. 修正冲刺方向逻辑
原代码冲刺时强制将direction设为Vector3.forward,会忽略左右输入,不符合第三人称冲刺的常规逻辑,应保留输入方向。
修正后的完整代码
public class ThirdPersonController: MonoBehaviour { public Rigidbody rb; public Transform _mainCamera; // 需在Inspector中赋值主相机 Vector3 direction; float speed; float RotationSmoothTime = 0.12f; float _rotationVelocity; bool walking; bool running; // 补充声明缺失的状态变量 void Update() { // 处理基础移动输入 if(_input.move.x != 0 || _input.move.y != 0) { walking = true; running = false; direction = new Vector3(_input.move.x, 0, _input.move.y).normalized; speed = 1.5f; } else { walking = false; // 补充静止状态处理 } // 处理冲刺输入(仅移动时可触发) if(_input.sprint && walking) { running = true; walking = false; speed = 3.0f; } else if(!walking) { running = false; } } void FixedUpdate() { Move(); } void Move() { if(direction.magnitude < 0.1f) { // 静止时平滑减速 rb.velocity = Vector3.Lerp(rb.velocity, Vector3.zero, Time.fixedDeltaTime * 5f); return; } // 计算目标旋转角度 float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + _mainCamera.transform.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref _rotationVelocity, RotationSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); // 计算相机空间下的移动方向 Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; moveDir.y = 0; // 锁定水平移动,避免干扰Y轴物理 // 平滑调整刚体速度,保留Y轴重力效果 Vector3 targetVelocity = moveDir.normalized * speed; targetVelocity.y = rb.velocity.y; rb.velocity = Vector3.Lerp(rb.velocity, targetVelocity, Time.fixedDeltaTime * 10f); } }
额外优化建议
- 将Rigidbody的
Interpolate属性设置为Interpolate或Extrapolate,进一步提升刚体运动的平滑度; - 检查角色碰撞体与场景中其他碰撞体是否存在穿透、摩擦异常,这类问题也可能导致移动抖动。
内容的提问来源于stack exchange,提问作者Omamuyovwi Lucky
相关产品推荐
相关产品推荐

