Unity2D相机旋转无法突破X轴-90度限制问题求助
解决Doom类游戏相机上下视角无法越过地平线的问题
你的问题根源在于直接操作相机的localRotation.eulerAngles,Unity的欧拉角采用0-360度的循环取值,当你尝试让X轴角度低于0度时,它会自动转换为360减去对应负值的结果(比如-90度会被转为270度),这就导致后续的鼠标输入偏移无法正确叠加,出现视角卡住的现象。
解决方法是单独维护一个变量跟踪垂直旋转角度,而非直接操作欧拉角,同时可以方便地限制视角范围(避免相机翻转到头顶或脚下),修改后的代码如下:
using UnityEngine; public class PlayerController : MonoBehaviour { public Rigidbody2D theRB; public float moveSpeed = 5f; private Vector2 moveInput; private Vector2 mouseInput; public float mouseSensitivity = 2f; public Transform viewCam; // 单独维护垂直旋转角度,避免欧拉角循环问题 private float verticalLookRotation = 0f; void Update() { // 玩家移动逻辑 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); Vector3 moveHorizontal = transform.up * moveInput.y; Vector3 moveVertical = transform.right * moveInput.x; theRB.velocity = (moveHorizontal + moveVertical) * moveSpeed; // 视角控制逻辑 mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * mouseSensitivity; // 水平旋转:控制玩家自身左右转向 transform.Rotate(0f, mouseInput.x, 0f); // 垂直旋转:更新角度并限制范围(经典Doom视角限制在±89度,避免翻转) verticalLookRotation -= mouseInput.y; verticalLookRotation = Mathf.Clamp(verticalLookRotation, -89f, 89f); // 根据垂直角度设置相机局部旋转 viewCam.localRotation = Quaternion.Euler(verticalLookRotation, 0f, 0f); } }
关键修改说明:
- 添加
verticalLookRotation变量存储垂直视角的实际角度,不受Unity欧拉角循环机制影响 - 用
transform.Rotate简化水平旋转逻辑,替代原来繁琐的欧拉角拼接 - 使用
Mathf.Clamp限制垂直角度在-89到89度之间,既解决了卡住问题,也符合Doom类游戏的经典视角体验
内容的提问来源于stack exchange,提问作者Guard Playz
相关产品推荐
相关产品推荐

