Determining whether to rotate left or right?

I have a situation where I want to rotate an object from currentRotation to targetRotation on the y axis. Is there a quick way to determine in code which way the object should rotate to get the shortest rotation? In this way, no rotation should be greater than 180 degrees.

This should work for all cases of currentRotation and targetRotation as either of them can be anything from 0-360 degrees. I think I found a way through a bunch of if, else statements, but I feel like I’m making it way too complicated.

Thanks!

Vector3 cross = Vector3.Cross(currentRotationVector3.forward, targetRotationVector3.forward);

turnRight = cross.y < 0;

If targetRotation is on the right of currentRotation, then the cross product between the forward directions will be negative. Be aware that the order in which you pass the directions into Vector3.cross is important!

Note: targetRotation*Vector3.forward is the forward direction of the object, if you were to apply the rotation.

Disclaimer: I am also relatively new to unity, hence may be missing some obvious function available in the unity library

“Easy to read” math algorithm using functions in unity (convert to degrees if inputs are in quaternions)

smallerAngle = Mathf.Min( currentRotation, targetRotation );
largerAngle = Mathf.Max( currentRotation, targetRotation );

turnRight = (largerAngle - smallerAngle) > 180.0f;

And I found the library funciton: Mathf.DeltaAngle

Cross product is going to be faster for 2D (you aren’t in a spaceship, spinning around) but if the “obvious” solution is really bugging you, imagine a grid glued to the player – you are always at (0,0,0), facing +z, and +x is always to your right, for this “personal” grid. You can find where the other guy is on your grid with:

Vector3 guyInMyCoords = transform.InverseTransformPoint(target.position);

Now, if gimc.X is positive, they are to your right. If gimc.Z is positive, they are in front of you. But, again, cross-product is faster.

I had the same problem, the best answer I’ve found:

float rotateDirection = (((targetRotation.eulerAngles.y - currentRotation.eulerAngles.y) + 360f) % 360f) > 180.0f ? -1 : 1;

from:

http://forum.unity3d.com/threads/determining-whether-to-rotate-left-or-right.139238/

To rotate on y:

Vector3 fromV = new Vector3(0, from , 0);
Vector3 toV = new Vector3(0, to , 0);

someObject.vector2rotation.y = Quaternion.LerpUnclamped(Quaternion.Euler(fromV),Quaternion.Euler(toV), 0.5f).eulerAngles.y;