# Converting Matrix4x4 to Quaternion & Vector3

I'm attempting to convert a Matrix4x4 which is being currently being applied to a camera using camera.worldToCameraMatrix and works fine.

I'm able to get the position out with:

``````Vector4 newCameraPos = matrix.GetColumn(3);
Camera.main.transform.position = Vector3(newCameraPos.x,newCameraPos.y,newCameraPos.z);

``````

But at the moment can't get the quaternion to come out. I've pulled some code from a matrix and quaternion FAQ I stumbled across and have partially implemented, but at the moment its not behaving.

``````Quaternion matrixToQuaternionx(Matrix4x4 m1){
float T = 1 + m1[0] + m1[5] + m1[10];

Quaternion q = Quaternion.identity;

if ( T > 0.00000001f ){
float S = Mathf.Sqrt(T) * 2;
q.x = ( m1[9] - m1[6] ) / S;
q.y = ( m1[2] - m1[8] ) / S;
q.z = ( m1[4] - m1[1] ) / S;
q.w = 0.25f * S;
}else{
Debug.Log("more to calculate here");
}

return q;
}

``````

If I turn off the camera.worldToCameraMatrix, and rely on the Vector and Quaternion I get out (ignoring cases where it gets to the 'more to calculate here') the position of the camera looks fine, but its rotation is way off.

For getting a quaternion from a Matrix4x4, this function works:

``````public static Quaternion QuaternionFromMatrix(Matrix4x4 m) {
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;
}

``````

For getting the position, GetColumn(3) works fine.

Here’s a faster and easier solution:

public static Quaternion QuaternionFromMatrix(Matrix4x4 m) {
return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
}