# Shortest Rotation Between Two Quaternions

Discussion in 'Scripting' started by imchrissharp, Jan 19, 2020.

1. ### imchrissharp

Joined:
May 2, 2018
Posts:
15
I am needing to get the shortest rotation path between two quaternions.

Quaternion a;
Quaternion b;

var c = a * Quaternion.Inverse(b);

c is usually the shortest path, but there are instances where it is the significantly longer rotation.

Is there an easy way to guarantee that c is always the absolute shortest rotation between a and b?

2. ### Kurt-Dekker

Joined:
Mar 16, 2013
Posts:
38,656
I think the Slerp operation is what you want:

https://en.wikipedia.org/wiki/Slerp

The reason I think this is that article mentions "great circle arc," which is of course what airliners do to get the shortest distance between distant airports.

3. ### SparrowGS

Joined:
Apr 6, 2017
Posts:
2,536
can you maybe check if the rotation of c is over 180/pie and if so just flip it?

4. ### imchrissharp

Joined:
May 2, 2018
Posts:
15
Hey Kurt good find, I was able to extract what I needed out of this. Here is the fix for anyone else running into this -

``````  public static Quaternion ShortestRotation(Quaternion a, Quaternion b)
{
if (Quaternion.Dot(a, b) < 0)
{
return a * Quaternion.Inverse(Multiply(b, -1));
}
else return a * Quaternion.Inverse(b);
}

public static Quaternion Multiply(Quaternion input, float scalar)
{
return new Quaternion(input.x * scalar, input.y * scalar, input.z * scalar, input.w * scalar);
}``````

5. ### Antistone

Joined:
Feb 22, 2014
Posts:
2,836
I think you are imagining that c is a float representing the angle between two vectors. In the example c is a Quaternion representing the rotation to get from one orientation to another.

6. ### SparrowGS

Joined:
Apr 6, 2017
Posts:
2,536
sorta but not really, just look if that rotation(c) is looking over 180 degrees from "0" rotation..?

I guess quaternion doesn't work anything like that eh?
lucky there's all of those functions, haha.

7. ### walaber_entertainment

Joined:
Jul 10, 2017
Posts:
30
This is exactly what I was looking for today. Thanks for sharing Guadinman!