Camera tilting when looking around

For an application in the cloud(Camera movement doesnt work in the cloud, after some research and testing I found out it doesn’t detect Input.GetAxis) I was asked to make the camera work in a different way.
The program could not register mouse movement, but could see the mouse position, so I tried using the old mouse position vs the new position to see if the mouse went left/right/up/down(This seemed like a pretty solid solution)

But the problem I’m having in this solution is that the camera “tilts”, I would think I would only go left/right/up/down, but somehow my camera sometimes slightly tilts/rotates when moving it around.

Any idea how to stop this from happening?

void Update()
    mouseY = Input.mousePosition.y;
    mouseX = Input.mousePosition.x;
    if (Input.GetKey(KeyCode.Mouse1) & (mouseY > mouseY2))
      Camera.main.transform.Rotate(new Vector3(-2, 0, 0));

    if (Input.GetKey(KeyCode.Mouse1) & (mouseY < mouseY2))
      Camera.main.transform.Rotate(new Vector3(2, 0, 0));

    if (Input.GetKey(KeyCode.Mouse1) & (mouseX > mouseX2))
      Camera.main.transform.Rotate(new Vector3(0, 2, 0));

    if (Input.GetKey(KeyCode.Mouse1) & (mouseX < mouseX2))
      Camera.main.transform.Rotate(new Vector3(0, -2, 0));
    mouseY2 = Input.mousePosition.y;
    mouseX2 = Input.mousePosition.x;

do you mean it is rotating at z axis too.

if i understand correctly, this problem caused by quartanion interpolation, which I usually don’t recommend to play with that.

if you are just looking for quick solution, just add rigidbody to your camera, uncheck use gravity , and freeze “z rotation” and done.

but if you want to learn whats going on in your code and what causing that tilt. start from here

This is not an answer. But it is some insight on an old “glitch”
with Unity’s First Person controller. the camera would rotate on the wrong axis
Don’t know if they fixed this or it has something to do with parenting.

I think you need to rotate along your Camera’s right and up vectors (right for up-down, and up for left-right rotation.

Also, when storing the mouse positions I wouldn’t query Input.mousePosition again, just simply write mouseY2 = mouseY and mouseX2 = mouseX.

This is such a typical question, I wonder why there isn’t a proper tutorial for it yet…