From: stormreaver

Written: 2009-01-10 16:01:41.788829

Subject: Aligning 3D Vectors

Written: 2009-01-10 16:01:41.788829

Subject: Aligning 3D Vectors

A very frequent operation in 3D programming is to align a vector with a target vector. This is a simple task that can be accomplished in two ways:

1) If you already have an axis of rotation.

a) Calculate the positive angle between the two vectors.

b) Construct two rotation matrices, one with the positive angle calculated above, and one with the corresponding negative angle.

c) Multiply the starting vector by the first matrix, storing the result in a different vector.

d) Multiply the unchanged starting vector by the second matrix, storing the result in a different vector.

e) Now calculate the unsigned angles between the two rotated vectors and the target vector. Use the angle from (b) above corresponding to the rotated angle that is now closer to the target vector.

There is

2) If you don't already have an axis of rotation, it's much easier.

a) Take the cross product between the two vectors. This will provide the axis of rotation.

b) Calculate the positive angle between the two vectors.

c) Rotate the first vector around the axis of rotation by the positive angle found in (b).

The cross product will automatically point in the right direction so that a rotation around the resulting vector by the positive angle between the two vectors will align them.

1) If you already have an axis of rotation.

a) Calculate the positive angle between the two vectors.

b) Construct two rotation matrices, one with the positive angle calculated above, and one with the corresponding negative angle.

c) Multiply the starting vector by the first matrix, storing the result in a different vector.

d) Multiply the unchanged starting vector by the second matrix, storing the result in a different vector.

e) Now calculate the unsigned angles between the two rotated vectors and the target vector. Use the angle from (b) above corresponding to the rotated angle that is now closer to the target vector.

There is

**no numeric method**to merely calculate a positive or negative angle between two 3D vectors, as sign is meaningless in 3D as far as angles between vectors are concerned. Angles between vectors are**always**positive. This doesn't mean that you can't perform a rotation by a negative number of degrees, but it does mean that calculating the angle between two vectors will**always**result in a positive number.2) If you don't already have an axis of rotation, it's much easier.

a) Take the cross product between the two vectors. This will provide the axis of rotation.

b) Calculate the positive angle between the two vectors.

c) Rotate the first vector around the axis of rotation by the positive angle found in (b).

The cross product will automatically point in the right direction so that a rotation around the resulting vector by the positive angle between the two vectors will align them.