Unity3D:类Minecraft第三人称移动系统水平移动绕相机旋转问题
问题原因
- 移动基准选择错误:你当前的移动方向是基于相机的前/右向量计算,而你要求移动基于玩家自身朝向,同时因为第三人称下相机会跟随玩家位移,相机的右向量会随玩家位置实时变化,最终导致按A/D时持续沿偏移的右侧方向移动,形成绕相机的圆周轨迹。
- 执行顺序错误:代码先执行移动逻辑,再更新玩家朝向,本次移动用的始终是上一帧的玩家朝向,进一步加大了位移偏差。
- 玩家旋转逻辑存在瑕疵:直接用
mainCameraTransform.forward计算朝向没有裁切y轴分量,可能导致玩家出现非预期的俯仰角度。
修复方案
调整执行顺序为「先更新玩家旋转→再基于玩家自身的前/右向量计算移动方向→最后执行位移」,修改后的代码如下:
// 先处理玩家旋转,对齐相机的水平朝向 Vector3 cameraForward = mainCameraTransform.forward; cameraForward.y = 0; // 裁切y轴分量,只保留水平朝向 cameraForward.Normalize(); transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(cameraForward), Time.deltaTime * 10f); // 再获取输入计算移动方向,基于玩家自身的前/右向量,符合移动基于自身朝向的需求 float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 playerForward = transform.forward; Vector3 playerRight = transform.right; playerForward.y = 0; playerRight.y = 0; playerForward.Normalize(); playerRight.Normalize(); Vector3 moveDirection = playerRight * horizontal + playerForward * vertical; Vector3 desiredMoveDirection = moveDirection * speed * Time.deltaTime; controller.Move(desiredMoveDirection);
如果你实际需求是WASD控制相对于相机方向移动、玩家自动面朝移动方向,可使用另一版适配代码:
float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 cameraForward = mainCameraTransform.forward; Vector3 cameraRight = mainCameraTransform.right; cameraForward.y = 0; cameraRight.y = 0; cameraForward.Normalize(); cameraRight.Normalize(); Vector3 moveDirection = cameraRight * horizontal + cameraForward * vertical; // 有输入时才旋转玩家朝向到移动方向 if (moveDirection.magnitude > 0.1f) { transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), Time.deltaTime * 10f); } Vector3 desiredMoveDirection = moveDirection * speed * Time.deltaTime; controller.Move(desiredMoveDirection);
内容的提问来源于stack exchange,提问作者user12791203
相关产品推荐
相关产品推荐

