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.
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.
Every frame this code takes in your Mouse movement turns it into a rotation using the familiar
Quaternion.Eulerfunction 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).