Animate rotating objects past 180 or -180 via code

Hello there. I am making a game where you can rotate a block. I do the “animation” by using coroutines with Quaternion.Lerp. As long as i am in between 180 and -180 it looks all good. But when i have a rotation of -180 and want to rotate -90 degrees, the lerp function does a backflip because it wants to go to +90. Any ideas?

I tried to check beforehand in which direction i want to rotate and then do for example:

 if (cubeRotator.transform.eulerAngles.x == -180)
     cubeRotator.transform.eulerAngles = new Vector3(

The coroutine looks something like this:

    IEnumerator HandleFlipping(Vector3 direction, float duration, Vector3 endPos)
 Quaternion targetRotation = Quaternion.Euler(targetFlip + cubeRotator.transform.rotation.eulerAngles);

       float time = 0;
       while (time < duration)
           cubeRotator.transform.rotation = Quaternion.Lerp(cubeRotator.transform.rotation, targetRotation, time / duration);
           time += Time.deltaTime;
           yield return null;

Also quick question, is transform.eulerAngles and transform.rotation.eulerAngles the same?

Just a hunch:
Quaternion targetRotation = Quaternion.Euler(targetFlip + cubeRotator.transform.rotation.eulerAngles);

Don't go through euler angles. You want targetFlip to be a quaternion so that you can do:
var targetRotation = targetFlip * cubeRotator.transform.rotation;

Note that multiplication is addition for Quaternions, and the order of multiplication actually matters.

1 Like