View Full Version : Rotation matrix from 2 vectors

 ofer_z03 March 2009, 01:30 PMHi, The title pretty much says it.. Given 2 vectors, how can I calculate the rotation matrix from vector 1 to vector 2? Thanks, o
Bobo
03 March 2009, 01:46 PM
Hi,

The title pretty much says it..
Given 2 vectors, how can I calculate the rotation matrix from vector 1 to vector 2?

Thanks,
o

You are looking for the matrix that transforms vector A into vector B. This will be a rotation matrix that corresponds to a quaternion with an arbitrary axis equal to the cross product of the two vectors and angle equal to the acos of the dot product. So you can calculate these two values, build a quaternion and convert to matrix3.

For example, create a teapot at the origin and give it some rotation.
Shift+rotate it at an arbitrary angle.
Now if you want to align the .dir (z axis) of the first to the second, you could say

z1 = \$Teapot01.dir
z2 = \$Teapot02.dir
theRotAxis = normalize (cross z2 z1)
theAngle = acos (dot z2 z1)
theQuat = quat theAngle theRotAxis
theTM = theQuat as matrix3
\$Teapot01.transform *= theTM

Note that this will not align all 3 axes of the teapots, only the Z axis. We have no knowledge of the full orientation of the teapots in space, only know where the Z are pointing at. theTM will be the value you are looking for.

ofer_z
03 March 2009, 10:39 PM