- Home /
Question by
martianfeline · Oct 27, 2021 at 03:55 PM ·
rotationquaternionclampclamped rotation
How to Clamp a Quaternion Camera Rotation?
I am trying to make a camera script which will rotate based on mouse movement. I have made most of what I wanted, but I am unsure how to clamp the camera to moving between certain values. Using Mathf.Clamp seems to not work on quaternions, and I haven't been able to come up with any other workarounds. Any help would be appreciated.
This is the code that deals with the rotation:
Quaternion camTurnAngleX = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationSpeed, Vector3.up);
Quaternion camTurnAngleY = Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * RotationSpeed, Vector3.right);
cameraOffset = camTurnAngleX * camTurnAngleY * cameraOffset;
The entire script is here:
[SerializeField] private Transform PlayerTransform;
private Vector3 cameraOffset;
[SerializeField, Range(0.01f, 1.0f)] private float Smooth;
[SerializeField] private float RotationSpeed;
private void Start()
{
cameraOffset = transform.position - PlayerTransform.position;
Cursor.lockState = CursorLockMode.Locked;
}
private void Rotate()
{
Vector3 newPos = PlayerTransform.position + cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, Smooth);
transform.LookAt(PlayerTransform);
Quaternion camTurnAngleX = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationSpeed, Vector3.up);
Quaternion camTurnAngleY = Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * RotationSpeed, Vector3.right);
cameraOffset = camTurnAngleX * camTurnAngleY * cameraOffset;
}
private void LateUpdate()
{
Rotate();
}
Comment