Align vector?

Looking for some general code that can align one 3D vector to another.

Or probably better, it should just return the rotation matrix to do the alignment.

Inputs : Vector v1, Vector V2.
V1 has to be aligned to V2 , by means of a matrix MT.
Steps involved :

  • Calculate the cross product of v1 and v2. Result is Vc
  • Calculate the angle between v1 and v2. Result is theta.
  • MT is the transformation of “Rotation about angle theta about vector Vc”

Hope this helps.
If I find some code… will post it for u .

morning rush

Forgot to add …
All vectors are normalized ( v1 and v2 are normalized).
Vc is normalised cross product of v1 and v2.
Angle can be calculated by
cos(theta) = v1 dot v2.

Thanks, found some code in graphics gems:
void Matrix::rotate(const Vector &from, const Vector &to);

I haven’t seen that code, but if it works anything like what Only Sophoo suggested, be aware that if the two vectors are exactly opposite of each other, their cross product will be zero and will not be usable as a rotation axis. You may want to check if the code deals with this scenario, and if not see

– Tom

I was looking in graphics gems for one, but I was mistaken, I got it from somewhere else.
Here is where I found it:
Right-handed Math Library, by David Poon:

And it does check for the cases you mentioned.