Sign in to follow this  
Spa8nky

Quaternion from Rotation Matrix always the same?

Recommended Posts

Spa8nky    230
If I create a rotation matrix from a forward vector using the following method:

[code]

public static Matrix RotationFrom(Vector3 forward)
{
// Forward
Vector3.Normalize(ref forward, out forward);

// Right
Vector3 right = Vector3.Cross(Vector3.UnitY, forward);

if (right.LengthSquared() < MathTools.EPSILON)
{
right = Vector3.Cross(-Vector3.UnitZ * Math.Sign(forward.Y), forward);
}

Vector3.Normalize(ref right, out right);

// Up
Vector3 up = Vector3.Cross(forward, right);
Vector3.Normalize(ref up, out up);

// Rotation
Matrix rotation = new Matrix();
rotation.Forward = forward;
rotation.Right = right;
rotation.Up = up;
rotation.M44 = 1f;

return rotation;
}
[/code]

Then the quaternion produced is the same for the following two forward vectors:

[code]

Quaternion q0 = MathTools.QuaternionFromRowMajorRotationMatrix(MathTools.RotationFrom(Vector3.UnitX));
Quaternion q1 = MathTools.QuaternionFromRowMajorRotationMatrix(MathTools.RotationFrom(Vector3.UnitY));

q0.Normalize();
q1.Normalize();

Console.WriteLine(q0);
Console.WriteLine(q1);
[/code]

{X:0 Y:0 Z:0 W:0.9999999}
{X:0 Y:0 Z:0 W:0.9999999}

If I use swap the order of the Cross Product in the same method:

[code]

public static Matrix RotationFromSwapped(Vector3 forward)
{
// Forward
Vector3.Normalize(ref forward, out forward);

// Right
Vector3 right = Vector3.Cross(forward, Vector3.UnitY);

if (right.LengthSquared() < MathTools.EPSILON)
{
right = Vector3.Cross(forward, Vector3.UnitZ * Math.Sign(forward.Y));
}

Vector3.Normalize(ref right, out right);

// Up
Vector3 up = Vector3.Cross(right, forward);
Vector3.Normalize(ref up, out up);

// Rotation
Matrix rotation = new Matrix();
rotation.Forward = forward;
rotation.Right = right;
rotation.Up = up;
rotation.M44 = 1f;

return rotation;
}
[/code]

then quaternion produced is not the same and is correct:

[code]

Quaternion q2 = MathTools.QuaternionFromRowMajorRotationMatrix(MathTools.RotationFromLH(Vector3.UnitX));
Quaternion q3 = MathTools.QuaternionFromRowMajorRotationMatrix(MathTools.RotationFromLH(Vector3.UnitY));

q2.Normalize();
q3.Normalize();

Console.WriteLine(q2);
Console.WriteLine(q3);
[/code]

{X:0 Y:-0.7071068 Z:0 W:0.7071068}
{X:0.7071068 Y:0 Z:0 W:0.7071068}

I use the first method to orientate my quadrangles and they always face the correct direction, so why is the same method giving me incorrect quaternions?

If I use the second method for my quadrangles then they face the opposite direction to the forward vector and are rotated incorrectly.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this