Unity摄像机X轴旋转限制异常问题求助
问题原因
问题出在你直接使用_currentCamera.transform.rotation.eulerAngles.x计算新角度。Quaternion的eulerAngles属性返回的X轴角度范围是0°到360°,而非你预期的-180°到180°。当摄像机向上旋转接近0°时,继续向上转的话,eulerAngles.x会跳转到360°附近(比如350°),此时计算出的newRotationX会远大于80°,被Mathf.Clamp直接钳到80°,导致摄像机突然向下跳。
修复方案
不要直接读取Quaternion的eulerAngles,而是维护一个独立变量跟踪X轴旋转偏移量,避免角度绕圈问题:
// 在类中添加私有变量跟踪摄像机X轴旋转 private float _cameraXRotation = 0f; private void RotateBodyWithMouse() { if (Input.GetMouseButton(1)) { Vector2 mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), -Input.GetAxisRaw("Mouse Y")); // 控制身体绕Y轴旋转 transform.Rotate(Vector3.up * mouseInput.x * _mouseSensitivity.x * Time.deltaTime); // 更新X轴旋转偏移量 _cameraXRotation += mouseInput.y * _mouseSensitivity.y * Time.deltaTime; // 钳制俯仰角度范围:-80°(向上最大角度)到80°(向下最大角度) _cameraXRotation = Mathf.Clamp(_cameraXRotation, -80f, 80f); // 将旋转应用到摄像机 _currentCamera.transform.rotation = Quaternion.Euler(_cameraXRotation, _currentCamera.transform.rotation.eulerAngles.y, 0f); } }
关键说明
- 独立变量
_cameraXRotation会保持在你设定的-80°到80°范围内,不会出现360°绕圈的异常情况。 - 摄像机仅修改X轴旋转实现俯仰限制,Y轴(水平旋转)和Z轴(倾斜)保持原有逻辑(Z轴设为0是因为通常不需要摄像机左右倾斜)。
内容的提问来源于stack exchange,提问作者Chen Robin
相关产品推荐
相关产品推荐

