Orienting along a vector


I need to be able to align objects along a vector. An example being a laser gun aiming at a target - so I need to be able to align it with the vector (enemy.origin - gun.origin).
I know, that in principle you take the “aim” vector as Z, then use some UP vector(Y) like the Y axis itself, build the cross product to get the orthonormal vector (-> X), then do a cross product with X and Z to get the Real Y…

But What do I do if the Z and Y vectors are almost parallel? Is there any formula to adjust the Up vector accordingly so that objects don’t flip?


[Edited PS:]
Right now I have to do the rotations with matrices, although I use quaternions for all other rotations.
Is there any way to calculate quaternions from an orthogonal vector pair or is the only way to get a quaternion a matrix->quaternion conversion?

[This message has been edited by Nick Nougat (edited 11-30-2002).]


I do basically the same thing you described in your first paragraph and havent had any problems with objects flipping.

The orientations of my objects are described by 3 vectors. I have a LookAt function for all objects which does precisely what you described, and it always works for me.

Even if you are directly over objects or are traversing in an arc from front to back over the top?
In theory the cross product gets 0 when two vectors are parallel and thus the resulting axis gets zero, right? Fitting this into a matrix should lead to problems - and with my implementation it does: The objects start turning around Z very quickly if abs(Z dot Y) gets near 0.98 and end up with inverted Y-axes. Re-Inverting the Y axis accordingly is not a big issue in itself, but preventing the objects from turning before Y gets inverted is…
If this really isn’t an issue with your implementation, would you mind showing me the piece of code you are using?


[This message has been edited by Nick Nougat (edited 01-10-2003).]

So, nobody has any additional ideas/opinions about this?

A possible solution which does not use quaternions and will eliminate the Gimbel lock you appear to be suffering from is to track the x’, y’, z’ orthogonal vectors and build your matrix directly from that.

See “Rotate a vector about another vector?” in this same discussion forum. Last entry was 1/8 or 1/9 last time I looked.

Thanks! That link in the post somewhow escaped my attention before… Looks promising.