- Home /
Wrong camera rotation value
I'm rotating the main camera around an object. for now only on the X axis. But I see some wierd values for the camera's rotaion. As I rotate it, I see the camera's rotation (Camera.main.transform.rotation.eulerAngles) goes up to 90 and then it goes back to 0, after 0 it suddenly jumps to 360 and continues to confuse me. also axis z and axis y change to 180 at some point
this is the code for the camera movement:
private void CameraMovement()
{
foreach (var touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
_previousPosition = _cam.ScreenToViewportPoint(touch.position);
}
else if (touch.phase == TouchPhase.Moved)
{
OnMouseMove(touch.position);
}
}
if (Input.GetMouseButtonDown(0))
{
_previousPosition = _cam.ScreenToViewportPoint(Input.mousePosition);
}
else if (Input.GetMouseButton(0))
{
OnMouseMove(Input.mousePosition);
}
}
private void OnMouseMove(Vector3 moveTo)
{
Vector3 newPosition = _cam.ScreenToViewportPoint(moveTo);
Vector3 direction = _previousPosition - newPosition;
_cam.transform.position = new Vector3(0, 0, 0);
_cam.transform.Rotate(new Vector3(1, 0, 0), direction.y * 180);
_cam.transform.Translate(new Vector3(0, 0, -distanceToTarget));
_previousPosition = newPosition;
}
Can anyone please explain to me why and how does it happen?
thanks!
Answer by bdubbert · Nov 11, 2021 at 11:08 PM
Rotations and orientations are represented in Unity with Quaternions. Quaternions work very elegantly as rotations and make manipulating them very easy. It is also worth noting that for any given rotation, there is exactly one corresponding Quaternion. However, Quaternions are mathematical mumbo jumbo to 99% of the population. There is a more human-readable way to represent rotations called Euler Angles. These are just the rotations about each axis you would need to do to get to the desired rotation. However Euler Angles suffer from several mathematical setbacks, one of which being that for any given rotation there are infinite euler angle representations. For example (0, 0, 0) represents the same rotation as (360, 0, 0). This is also true for more complex euler angles, for example (421, 74, -150) = (119, -106, 30).
So when you ask Unity for the euler angles for a rotation, it will calculate the single simplest euler representation. However as you rotate your object around, the simplest euler representations between two adjacent rotations may not resemble eachother at all. This is where you get all of your crazy jumping numbers, you are transitioning between rotations whose simplest euler angles don't look very close to eachother even though the corresponding rotations are very close to eachother.
If you want to calculate euler angles that change smoothly with rotation there are ways to do that, but Unity only knows to give you the simplest euler angles when you ask.