- Home /
Camera global rotation clamping issue
I have a problem, I'm making an smooth camera movement script, and I can't figure out how to clamp correctly camera rotation.
Actually, camera is a child of player object.
When WASD is pressed the player is rotated, but the camera doesn't follow this rotation because of the script.
var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
mouseDelta = Vector2.Scale(mouseDelta, CursorSensitivity); //new Vector2(CursorSensitivity.x * smoothing.x, CursorSensitivity.y * smoothing.y));
if (m_doSmooth)
{
_smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x);
_smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y);
// Find the absolute mouse movement value from point zero.
_mouseAbsolute += _smoothMouse;
}
else
_mouseAbsolute += mouseDelta;
if (clampInDegrees.x > 0)
_mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x, clampInDegrees.x);
if (clampInDegrees.y > 0)
_mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y, clampInDegrees.y);
Camera.transform.rotation = Quaternion.AngleAxis(-_mouseAbsolute.x, Vector3.up) //transform.InverseTransformDirection(Vector3.up))
* Quaternion.AngleAxis(_mouseAbsolute.y, Vector3.right);
Well, the problem is easy, the clamped rotation values are global, because we set Camera.transform.rotation
instead of Camera.transform.localRotation
.
And this happens: Link to video
The script clamps values according to player rotation.
So if we have a rotation (eulerAngle) on the player on the X axis of 90 degrees, and clamp value is from 90 to -90, the clamped rotation will be 0, 180, instead of -90, 90.
But if I change from rotation
to localRotation
this happens: Link to video
I also tried the following:
Vector3 euler = Camera.transform.eulerAngles;
if (clampInDegrees.x > 0)
euler.x = ClampAngle(euler.x, -clampInDegrees.x, clampInDegrees.x);
if (clampInDegrees.x > 0)
euler.y = ClampAngle(euler.y, -clampInDegrees.y, clampInDegrees.y);
Camera.transform.eulerAngles = euler;
After setting localRotation
... But this only make weird things. Like for example, when reaching the min clamp value at rotating the clamp returns the max clamp value.
Your answer
![](https://koobas.hobune.stream/wayback/20220612164659im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Clamping Rotation 2 Answers
Constraints on rotation axis in c# 1 Answer
how to clamp y axis with Quaternion.Euler in unity 1 Answer
Multiple Cars not working 1 Answer