0
\$\begingroup\$

I'm trying to rotate a character on along the y axis but rather than continuing to rotate, it rotates then the y rotation goes back to 0. I'm not sure what I'm doing wrong. The same thing happens if I change the rotation in the inspector. The line that's causing this is the second one in the Look Function.

public void Look()
{
    Quaternion Rotation = transform.rotation;
    Rotation = Quaternion.Euler(transform.rotation.x , transform.rotation.y + Input.GetAxis("Mouse X"), transform.rotation.z);
    rb.rotation = (Rotation);
}
\$\endgroup\$
1
\$\begingroup\$

Don’t animate using Euler angles. From the Unity docs:

There are some situations where it is valid to use Euler angles, but you should bear in mind: - You should use the Quaternion Class functions that deal with Euler angles - Retrieving, modifying, and re-applying Euler values from a rotation can cause unintentional side-effects.

You should also avoid assigning rotation directly when animating. Instead, use Rigidbody.MoveRotation, which also takes interpolation into account:

public void Look() {
  Quaternion rotation = Quaternion.AngleAxis(Input.GetAxis("Mouse X"), Vector3.up)
  rb.MoveRotation(rb.rotation * rotation);
}

Here I used Quaternion.AngleAxis to create a rotation around the Y-axis (the Vector3.up axis) and then Quaternion multiplication to apply it to the existing rotation.

Note that the problem you saw was due to the fact that you were treating the Quaternion as a vector, expecting the x, y, and z components of the Quaternion to be the same as the Euler angle version you assign it to. This is not the case. You can read more about the difference between quaternions and Euler angles in the first link above to the Unity docs.

\$\endgroup\$
  • \$\begingroup\$ Missing a semicolon on second line \$\endgroup\$ – Michael McQuade May 1 '19 at 23:51
1
\$\begingroup\$

As long as you haven't changed the default input settings in the project settings Input.GetAxis("Mouse X") will not return the mouse position but the acceleration of the mouse in a certain direction ranging from -1 to 1. This results in your game object rotating at a maximum of one degree depending on the speed you move your mouse.

I'll suggest using Input.mousePosition.x as this returns the mouse position on the x-axis on the screen which will be added to the rotation value resulting in a full rotation of your game object every 360 pixels the mouse travels along the x-axis.

Please note, that Ed Marty is completely right! You should never use Euler angles for animation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.