Unity.Mathematics equivalent to Quaternion.FromToRotation?

I’m building a game using DOTS and am adding support to a first-person controller allowing the player to walk around a sphere.

My understanding is that I could use Quaternion.FromToRotation in the non-DOTS world to rotate my player character so they stay properly aligned to the sphere as they walk around. I haven’t been able to find anything equivalent in Unity.Mathematics. Does anyone know if it exists?

I found this - which looks helpful. Worst case, I can attempt to transcribe MyQuaternion.FromToRotation to a Unity.mathematics.quaternion equivalent. I’m no quaternion expert, though, so I’d prefer to avoid this, if possible.

Can anyone point me in the direction of any helpful resources? Ultimately, I want to understand quaternions in-depth, so resources for that would be much appreciated too!


using Unity.Mathematics;
public static quaternion FromToRotation ( float3 from , float3 to )
=> quaternion.AxisAngle(
angle: math.acos( math.clamp(math.dot(math.normalize(from),math.normalize(to)),-1f,1f) ) ,
axis: math.normalize( math.cross(from,to) )

Go say thanks to: @Bunny83 Whats the source code of Quaternion.FromToRotation? - Questions & Answers - Unity Discussions

Well, FromToRotation shouldn’t be that difficult. Since a quaternion always represents a rotation around one specific axis, the axis we’re looking for is simply the cross product between your two directions. The required angle around that axis is simply the angle between the two vectors. Then you should be able to just use that axis and the angle with AxisAngle.

To calculate the angle you would just calculate the dot product between your two (normalized) vectors and then use acos to get the angle

Thank you @andrew-lukasik and @Bunny83, this is exactly what I was looking for.

I pasted the code provided into a class (with some formatting applied):

using Unity.Mathematics;

public static class Quat {
  public static quaternion FromToRotation (float3 from , float3 to) =>
      angle: math.acos(
      axis: math.normalize(math.cross(from, to))

I then used this new class as follows:

float3 dir = planetTranslation.Value - playerTranslation.Value;

quaternion rotate = Quat.FromToRotation(new float3(0, -1, 0), dir);

playerRotation.Value = rotate;

Another aspect of this that was confusing me is what to actually pass as arguments to FromToRotation. This helped me understand.

In my case, I want the bottom of my player to point to the center of the planet they are walking on. Said another way: I want my player’s down vector (new float3(0, -1, 0)) to rotate toward (or face) the center of the planet.

To achieve this, I pass the down vector as the first argument (telling FromToRotation this is the vector I want to change) and I pass dir (the direction pointing from the player to the center of the planet, as a vector) as the second argument (telling FromToRotation that this is where to rotate the player’s down vector to).