Limit Horizontal Rotation

I have this function, that rotates the object and the camera associated with the object moving the mouse nicely.

My problem is that the clamp isn’t working as intended, I have been trying a few things I found searching but none of them seems to work.

I want the rotation to be clamped betweent -40 and 40 (degrees) but the Clamp is clamping it between 0 and 40 because as soon as the object rotates to <0 degrees, it’s actually 359º with is bigger than 40º so it moves back to 40 degrees.

   private void Look()
        _mouseX = Input.GetAxis("Mouse X");
        _mouseY = Input.GetAxis("Mouse Y");
        Vector3 newRotation = transform.localEulerAngles;

        newRotation.y += _mouseX * _sensibility * Time.deltaTime;
        newRotation.x += -_mouseY * _sensibility * Time.deltaTime;

        newRotation.y = Mathf.Clamp(newRotation.y, -40f, 40f);

        transform.localEulerAngles = newRotation;

Thank you :slight_smile:

I posted this for someone earlier today. It is easier to handle the rotation on two transforms. So make your camera a child of another gameobject and attach the script to the parent.

using UnityEngine;

public class MouseLook : MonoBehaviour
    public float Sensitivity = 2f;
    public float YAxisAngleLock = 90f;

    public Transform CameraTransform;

    private Transform _playerTransform;

    private Vector2 _rotation;
    private Quaternion _playerTargetRot;
    private Quaternion _cameraTargetRot;

    private void Start()
        _playerTransform = transform;
        _playerTargetRot = _playerTransform.rotation;
        _cameraTargetRot = CameraTransform.rotation;

    private void LateUpdate()
        _rotation.x = Input.GetAxis("Mouse X") * Sensitivity;
        _rotation.y = Input.GetAxis("Mouse Y") * Sensitivity;

        _playerTargetRot *= Quaternion.Euler(0f, _rotation.x, 0f);

        _cameraTargetRot *= Quaternion.Euler(-_rotation.y, 0f, 0f);

        _cameraTargetRot = LockCameraMovement(_cameraTargetRot);

        _playerTransform.localRotation = _playerTargetRot;
        CameraTransform.localRotation = _cameraTargetRot;

    private Quaternion LockCameraMovement(Quaternion q)
        q.x /= q.w;
        q.y /= q.w;
        q.z /= q.w;
        q.w = 1.0f;

        float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x);

        angleX = Mathf.Clamp(angleX, -YAxisAngleLock, YAxisAngleLock);

        q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX);

        return q;