无法让我的相机正确限制其旋转

在我的游戏中,我想要夹住玩家的相机,这样就无法进行前翻或后翻。 我想将x轴夹在-75和50之间,但它不起作用。

每当我在我的代码中添加一个钳位时,相机就不希望将它的旋转距离输入的距离为0,0,0.GetAxisRaw表示鼠标正在移动。

我已尝试将if语句用作手动钳位,但如果我切换极性,它会不断地保持在0,0,0或恒定地保持在-75,0,0。

我已经尝试更换相机,以防它与其设置相关但没有任何变化。

我不想发布这个,因为它不应该这么难,但我已经花了好几天时间而且我没有选择; 任何和所有的想法都非常感激。

我使用Visual Studio作为我的编辑器。

using UnityEngine; public class PlayerMove : MonoBehaviour { Rigidbody rb; public Camera cam; public Transform camTrans; Vector3 movement; Vector3 rotation; public float sensitivityX; public float sensitivityY; public float playerSpeed; public float jumpForce; float forward; float sideways; void Start() { rb = GetComponent(); } void FixedUpdate () { forward = Input.GetAxisRaw("Vertical"); sideways = Input.GetAxisRaw("Horizontal"); movement = new Vector3 (forward, 0, -sideways).normalized; float _xRot = Input.GetAxisRaw("Mouse Y"); float _yRot = Input.GetAxisRaw("Mouse X"); rotation = new Vector3(0f, _yRot, 0f) * sensitivityX; float _jump = Input.GetAxisRaw("Jump"); if (movement != Vector3.zero) { MovePlayer(); } if (rotation != Vector3.zero && Input.GetAxisRaw("Fire2") != 0 || _xRot != 0 && Input.GetAxisRaw("Fire2") != 0) { Rotate(-_xRot); } if (_jump != 0f) { Jump(); } } void MovePlayer() { float _playerSpeed; _playerSpeed = playerSpeed * 0.1f; transform.Translate(movement * _playerSpeed * Time.fixedDeltaTime, Space.Self); } void Jump() { if (IsGrounded()) { rb.AddForce(new Vector3(0, 1 * jumpForce, 0), ForceMode.Impulse); } } void Rotate(float _camRot) { camTrans.Rotate(new Vector3(_camRot * sensitivityY, 0, 0)); float _camPosX = camTrans.rotation.x; Mathf.Clamp(_camPosX, -75, 50); camTrans.rotation = Quaternion.Euler(new Vector3(_camPosX, 0, 0)); rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation * sensitivityX)); } bool IsGrounded() { RaycastHit hit; return Physics.Raycast(transform.position, Vector3.down, out hit, 1.001f); } } 

Input.GetAxisRaw("Mouse Y"); 返回鼠标移动的单位数(请参阅Unity文档 – Input.GetAxisRaw )。

当您移动鼠标时,脚本可以正常工作,但因为void Rotate()Update()函数中调用了每一帧,在一些帧之后输入了Input.GetAxisRaw("Mouse Y") ; 返回0然后_camRot = 0

所以, camTrans.rotation = Quaternion.Euler(new Vector3(0, 0, 0)); 并且因为Update()每秒调用多次,我们认为摄像机不断地保持在0,0,0。

要限制旋转,您可以将代码更改为:

 public class PlayerMove : MonoBehaviour { ... private float rotationX; ... void Rotate(float _camRot) { rotationX += _camRot * sensitivityY; rotationX = Mathf.Clamp(rotationX, -75, 50); camTrans.localEulerAngles = new Vector3(rotationX, camTrans.localEulerAngles.y, camTrans.localEulerAngles.z); rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation * sensitivityX)); } } 

我希望它对你有所帮助。