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;
                _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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.