- Home /
What is the source code of Quaternion.LookRotation?
Is there some reference where I can see the native source code? Or similar implementation elsewhere?
Answer by vladibo · Jun 03, 2013 at 11:17 AM
This is what I was able to come out with. Seems to work. Just note that forward and up vector must be orthogonal, the function doesn't have orthogonization of up vector.
private static Quaternion QuaternionLookRotation(Vector3 forward, Vector3 up)
{
forward.Normalize();
Vector3 vector = Vector3.Normalize(forward);
Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector));
Vector3 vector3 = Vector3.Cross(vector, vector2);
var m00 = vector2.x;
var m01 = vector2.y;
var m02 = vector2.z;
var m10 = vector3.x;
var m11 = vector3.y;
var m12 = vector3.z;
var m20 = vector.x;
var m21 = vector.y;
var m22 = vector.z;
float num8 = (m00 + m11) + m22;
var quaternion = new Quaternion();
if (num8 > 0f)
{
var num = (float)Math.Sqrt(num8 + 1f);
quaternion.w = num * 0.5f;
num = 0.5f / num;
quaternion.x = (m12 - m21) * num;
quaternion.y = (m20 - m02) * num;
quaternion.z = (m01 - m10) * num;
return quaternion;
}
if ((m00 >= m11) && (m00 >= m22))
{
var num7 = (float)Math.Sqrt(((1f + m00) - m11) - m22);
var num4 = 0.5f / num7;
quaternion.x = 0.5f * num7;
quaternion.y = (m01 + m10) * num4;
quaternion.z = (m02 + m20) * num4;
quaternion.w = (m12 - m21) * num4;
return quaternion;
}
if (m11 > m22)
{
var num6 = (float)Math.Sqrt(((1f + m11) - m00) - m22);
var num3 = 0.5f / num6;
quaternion.x = (m10+ m01) * num3;
quaternion.y = 0.5f * num6;
quaternion.z = (m21 + m12) * num3;
quaternion.w = (m20 - m02) * num3;
return quaternion;
}
var num5 = (float)Math.Sqrt(((1f + m22) - m00) - m11);
var num2 = 0.5f / num5;
quaternion.x = (m20 + m02) * num2;
quaternion.y = (m21 + m12) * num2;
quaternion.z = 0.5f * num5;
quaternion.w = (m01 - m10) * num2;
return quaternion;
}
is this the actual implementation in unity or u have come up with this ?
We don't know the exact implementation of Unity's LookRotation method as it's defined in native code.
I have not confirmed the code here is right, but it looks like he's using pretty much the same approach mentioned here at the end.
Answer by Graham-Dunnett · Jun 02, 2013 at 08:35 PM
Dunno what the source code is exactly, but normalize the vectors, take a cross product, then you have 3 vectors that will form a rotation matrix. (So, (0,0,1) multiplied by M
gives forward, (0,1,0) multiplied by M
gives upward, and (1,0,0) multiplied by M
gives right.) Now you have a rotation matrix, so google and get:
which tells you how to get from a matrix to a quaternion.
(You can, of course, license the source code to Unity if you really need to know exactly what's happening under the hood.)