- Home /
Why rotating around X and Y axis using transform.Rotate rotates around z axis as well ?
I am trying to make a camera controller kind of scripts like in a fps. I am using the following code to rotate the camera with the mouse input .:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Final_Camera_Controller : MonoBehaviour
{
private float rx;
private float ry;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ry = Input.GetAxis("Mouse Y");
transform.Rotate(-ry,0f,0f);
rx = Input.GetAxis("Mouse X");
transform.Rotate(0f,rx,0f);
}
}
Initially I was trying using one transform.Rotate passing both rx and -ry then tried them separately , still no benfit..
Answer by Bunny83 · Sep 20, 2019 at 12:37 AM
Because that's how 3d rotations work ^^. Just take any object you have in reach and try it yourself. Transform.Rotate by default rotates around local space axes. Just imagine rotating an object around it's local up axis 90° clockwise. So "forward" now points to the right and "up" still points up. Now do a 90° rotation around the local right axis (which is currently -forward in worldspace). As result the object's forward axis will point upwards and the local up axis will point to the left in worldspace. Now just rotate counter clockwise on the local y axis again and forward is again forward as in the beginning. However the object is now rotated 90° counter clockwise on z.
Actual 3d open space games (like space engineers) have additional keys to roll since in space there's no reference to "the ground" since there is no ground.
FPS games usually want to keep the camera parallel to the horizon. For this you generally want to rotate around the global Y-axis and the local X-axis.
void Update()
{
ry = Input.GetAxis("Mouse Y");
transform.Rotate(-ry,0f,0f, Space.Self);
rx = Input.GetAxis("Mouse X");
transform.Rotate(0f,rx,0f, Space.World);
}
Of course relative rotations can still cause a slight tilt over time since slight errors can accumulate. That's why it's common to work with absolute rotation angles which you change with your mouse input. This is also necessary if you want to limit the rotation of one of those axis. Usually FPS game characters are even splitted into two parts:
the body which only rotates around the global Y axis
the head / camera which only rotates around the local X axis
Your answer
