Unity角色左移时被物体遮挡/穿模,右移正常的问题求助
Unity角色左移穿模/显示异常问题排查与解决
控制玩家角色向左移动时,角色出现穿入场景物体内部或显示在物体后方的异常状态,但向右移动时显示完全正常。相关PlayerMovement脚本代码如下:
using UnityEngine; public class PlayerMovement : MonoBehaviour { public float moveSpeed = 5f; public float rotationSpeed = 10f; private Rigidbody rb; private Animator animator; void Start() { rb = GetComponent<Rigidbody>(); animator = GetComponent<Animator>(); } void Update() { // Handle animations in Update float moveX = Input.GetAxis("Horizontal"); animator.SetFloat("Speed", Mathf.Abs(moveX * moveSpeed)); // Ensure Speed is a positive value animator.SetBool("Grounded", true); // Assuming the player is always grounded in this example } void FixedUpdate() { // Handle physics in FixedUpdate float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime; // Move the player only on the x-axis Vector3 newPosition = rb.position + new Vector3(moveX, 0f, 0f); rb.MovePosition(newPosition); // Rotate to face the direction of movement if (moveX != 0) { Vector3 targetDirection = new Vector3(moveX, 0f, 0f); Quaternion targetRotation = Quaternion.LookRotation(targetDirection); rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime); } } }
可能原因与解决方法
1. 碰撞体设置问题
- 检查玩家角色碰撞体:确保碰撞体的中心位置和大小完全覆盖角色模型,左移时无偏移导致穿模。
- 检查场景物体碰撞体:确认障碍物碰撞体完整,无缺失或错误设置。
- 将玩家碰撞体的碰撞检测模式改为
Continuous或Continuous Dynamic,避免高速移动时碰撞检测遗漏(左移方向可能因旋转导致检测延迟)。
2. 移动与旋转逻辑冲突
当前代码用LookRotation基于X轴方向旋转,但LookRotation默认指向Z轴正方向,导致局部与世界坐标系冲突,影响碰撞判定:
- 修改旋转逻辑,直接控制Y轴旋转角度:
// 替换FixedUpdate中的旋转代码 if (moveX != 0) { float targetYRotation = moveX > 0 ? 0f : 180f; // 右移朝0度,左移朝180度 Quaternion targetRotation = Quaternion.Euler(0f, targetYRotation, 0f); rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime); }
3. 渲染层级与遮挡问题
- 检查玩家角色和场景物体的Sorting Layer设置,确保玩家角色的排序层优先级更高,避免左移时被错误遮挡。
- 调整角色模型的Z轴位置偏移,确保模型与碰撞体位置匹配,无动画或模型 pivot 点错误导致的显示偏移。
4. 动画根运动冲突
结合Animator控制器截图检查:
- 关闭动画的Root Motion:在Animator组件中取消勾选
Apply Root Motion,确保所有位移由脚本控制,避免动画与脚本移动逻辑冲突。 - 检查混合树中左右移动动画的位移设置,确保左移动画无额外的位置偏移。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

