Camera gets inverted when turning 180 degrees vertically in Unity

155 Views Asked by At

When I am turning my camera 180 degrees vertically the horizontal input gets inverted

using UnityEngine;

public class FreeLookCamera : MonoBehaviour
{
    public float sensitivity = 2.0f;

    private float rotationX = 0.0f;
    private float rotationY = 0.0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");

        rotationY += mouseX * sensitivity;
        rotationX -= mouseY * sensitivity;

        transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
    }
}

I was trying to make a space movement system where the camera could look anywhere without any constraints.

1

There are 1 best solutions below

0
Voidsay On

You're using a global frame of reference for your axis rotations. Turning horizontally always results in the same rotation on the y axis no matter how the camera is oriented.

To make a truly free camera you need to rotate relative to the cameras current orientation. Doing so with typical euler angles gets complicated quickly and you'll run into the gimbal lock effect. You can avoid all that by using quaternions.

using UnityEngine;

public class FreeLookCamera : MonoBehaviour
{
    public float sensitivity = 2.0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        float rotationY = Input.GetAxis("Mouse X") * sensitivity;
        float rotationX = - Input.GetAxis("Mouse Y") * sensitivity;

        transform.rotation *= Quaternion.Euler(rotationX, rotationY, 0);
    }
}

Every frame this code takes in your Mouse movement turns it into a rotation using the familiar Quaternion.Euler function and adds it to the current rotation of the camera. To keep the explanation short, you can add two rotations by multiplying their quaternions (because matrix math).