I have fragment of code that has to rotate the camera to the direction where my cursor is as below:

float yaw = mouseSensitivity.x * Input.GetAxis("Mouse X");
float pitch = mouseSensitivity.y * -Input.GetAxis("Mouse Y");

Vector3 camRotDir = new Vector3(pitch, yaw, 0);

// this works 
Vector3 camRot = mPlayerCamera.transform.rotation.eulerAngles + camRotDir;
mPlayerCamera.transform.rotation = Quaternion.Euler(camRot);

// this doesn't work
//var rotation = Quaternion.Euler(camRotDir);
//mPlayerCamera.transform.rotation =  mPlayerCamera.transform.rotation * rotation;

WithmouseSensitivity being an arbitrary Vector2 value representing mouse's sensitivity respectively on axis X and Y.

The problem is when I convert the current camera's rotation in Quaternion to Euler angle, add the camRotDir to it and then convert the result back to Quaternion, it works properly, the z component in camera's rotation remains unchanged during this process. But when I first convert the camRotDir to Quaternion and add it to camera's current rotation by multiplying them together, I get unexpected behaviour, the z component was somehow changed.

I have no idea why this happens, should Quaterion of (euler_a + euler_b) == (Quaternion of euler_a) * (Quaternion of euler_b) ?

Code run in Unity 2018.3.12f1.

  • 1
    \$\begingroup\$ You're running into a common misconception of how rotation works in three dimensions. I've tried to explain this, and what you can do about it, with animated examples in this Q&A. Generally we should not expect the sum of two Euler angles to in any way correspond to the composition of two rotations. Euler angles aren't really made to be added and subtracted, and you can easily get unwanted results when you try to do math on them. A yaw-pitch camera is a special case where Euler angles behave reasonably intuitively. \$\endgroup\$
    – DMGregory
    Commented Oct 14, 2019 at 11:59
  • \$\begingroup\$ @DMGregory excellent explanation, thank you for sharing your knowledge. \$\endgroup\$
    – tc07
    Commented Oct 14, 2019 at 12:44


Browse other questions tagged .