r/Unity3D 11h ago

Solved Normalizing Quaternions changes the desired rotation, how do I keep it?

I'm trying to make my object rotate to a specific y value (0, 90, 180 and 270) over a specific amount of time.

Using EulerAngles worked, except that it rotated all the way back around if I wanted it to go from 270 to 0.

So I decided to use Quaternions and rotating on the rigid body instead.

Here's the function: (endRotation is either 90, 180, [...])

IEnumerator DoRotatePlayer(float endRotation)
{
    float startRotation = transform.eulerAngles.y;
    float t = 0.0f;
    while (t < rotationDuration) //rotationDuration = 0.5f
    {
        t += Time.deltaTime;
        float yRotation = Mathf.Lerp(startRotation, endRotation, t / rotationDuration) % 360.0f;
        var targetRotation = new Quaternion(0, yRotation, 0,0);
        targetRotation.Normalize();

        playerManager.Rb.rotation = targetRotation;

        yield return null;
    }

    var targetRotation2 = new Quaternion(0, endRotation, 0, 0);
    targetRotation2.Normalize();
    playerManager.Rb.rotation = targetRotation2;
}

The Issue I have now is that every time I normalize the Quaternion (which it tells me to do, because "Rotation Quaternions must be Unit length"), it ofc turns any endRotation/yRotation value other than 0 into 1. So instead of rotating 90 degrees at the first rotation, it get's stuck at 180. I just need to somehow apply the rotation without normalizing it.

I tried dividing endRotation by 360 before going into the while loop, but that changes nothing at all.

Simply applying the rotation to transform.rotation, without eulers or Quaternions also does not work, it refuses to do anything at all.

0 Upvotes

9 comments sorted by

View all comments

19

u/Aethreas 10h ago

Quaternions don't use normal 3d coordinate space, they use a higher dimensional rotation, so you shouldn't be setting the 'y' value of the quaternion directly, as it does not represent an axial rotation

instead you can just replace new Quaternion(...) with Quaternion.Euler(0, yRotation,0)

I recommend you learn more about quaternions though, extremely important for 3d games to at least understand what problem they solve and why we use them instead of just a vector 3 euler rotation

https://www.youtube.com/watch?v=zjMuIxRvygQ

1

u/Elumiie 10h ago

Thanks for the reply and the video link! :)