I have a coord system in space that has its forward, up and right vectors. Its not an object so I cant use its transform.forward, transform.up and transform.right. These three vectors are orthonormal.
I would like to know its rotation in quaternion form. Usualy we could do that using transform.rotation but since its not an object we cant.
Untested, but should work…
C#
Vector3 forward, right, up;
Matrix4x4 M = new Matrix4x4();
M.SetColumn(0, right);
M.SetColumn(1, up);
M.SetColumn(2, forward);
Quaternion Q = QuaternionFromMatrix(M);
...
public static Quaternion QuaternionFromMatrix(Matrix4x4 m) {
// Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
Quaternion q = new Quaternion();
q.w = Mathf.Sqrt( Mathf.Max( 0, 1 + m[0,0] + m[1,1] + m[2,2] ) ) / 2;
q.x = Mathf.Sqrt( Mathf.Max( 0, 1 + m[0,0] - m[1,1] - m[2,2] ) ) / 2;
q.y = Mathf.Sqrt( Mathf.Max( 0, 1 - m[0,0] + m[1,1] - m[2,2] ) ) / 2;
q.z = Mathf.Sqrt( Mathf.Max( 0, 1 - m[0,0] - m[1,1] + m[2,2] ) ) / 2;
q.x *= Mathf.Sign( q.x * ( m[2,1] - m[1,2] ) );
q.y *= Mathf.Sign( q.y * ( m[0,2] - m[2,0] ) );
q.z *= Mathf.Sign( q.z * ( m[1,0] - m[0,1] ) );
return q;
}
Reference:
Converting Matrix4x4 to Quaternion Vector3
This Matrix to Quaternion method was provided by runevision on Unity Answers.
That’s it, thank you.
Thank you, worked like a charm)
Thanks - there is a second answer now (on the same page). After testing both I found it to be more accurate:
public static Quaternion QuaternionFromMatrix(Matrix4x4 m)
{
return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
}