- Home /
Rotating a camera that is already rotated on Z axis
Context:
With the help of a few tutorials I wrote a simple, FPS-like, camera script. It translates the horizontal mouse movement to camera's rotation on Y axis and vertical mouse movement to camera's rotation on X axis.
The problem:
This works as long as the camera is not rotated on Z axis (and unfortunately, I will have to rotate the camera this way in my game). When the camera is rotated on Z axis by about 90 degrees, horizontal mouse movement causes the camera to rotate on X axis while vertical movements - on Y axis. This is the opposite of what I want.
Here is a link to gif images with descriptions that show:
-> how I can control the camera when it's not rotated on Z axis
-> how I cannot control the camera the way I want when it is rotated on Z axis
-> what effect I wish to achieve
https://imgur.com/a/6hyMRGI
And here is my current code controlling the camera:
using UnityEngine;
public class camtemp : MonoBehaviour {
public float lookSensitivity = 5.0f;
private float xRotation;
private float yRotation;
private void Awake()
{
Vector3 startRotation = transform.rotation.eulerAngles;
xRotation = startRotation.x;
yRotation = startRotation.y;
}
private void Update()
{
yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
// This stops the player from rotating too far on X axis
xRotation = Mathf.Clamp(xRotation, -90, 90);
transform.rotation = Quaternion.Euler(xRotation, yRotation, transform.rotation.eulerAngles.z);
}
}
I fail to understand why it works this way. Any help would be greatly appreciated :)