# Question Animate rotating objects past 180 or -180 via code

Discussion in 'Scripting' started by donrigo, Nov 30, 2023.

1. ### donrigo

Joined:
Sep 23, 2020
Posts:
1
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:
Code (CSharp):
1.
2.  if (cubeRotator.transform.eulerAngles.x == -180)
3.  {
4.      cubeRotator.transform.eulerAngles = new Vector3(
5.          -cubeRotator.transform.eulerAngles.x,
6.          cubeRotator.transform.eulerAngles.y,
7.          cubeRotator.transform.eulerAngles.z);
8.  }
9.
The coroutine looks something like this:
Code (CSharp):
1.
2.     IEnumerator HandleFlipping(Vector3 direction, float duration, Vector3 endPos)
3.  {
4.  Quaternion targetRotation = Quaternion.Euler(targetFlip + cubeRotator.transform.rotation.eulerAngles);
5.
6.        float time = 0;
7.        while (time < duration)
8.        {
9.            cubeRotator.transform.rotation = Quaternion.Lerp(cubeRotator.transform.rotation, targetRotation, time / duration);
10.            time += Time.deltaTime;
11.            yield return null;
12.        }
13.
Also quick question, is transform.eulerAngles and transform.rotation.eulerAngles the same?

Last edited: Nov 30, 2023
2. ### CodeSmile

Joined:
Apr 10, 2014
Posts:
5,078
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.

donrigo likes this.