Skip to main content
GameDev.net gamedev.net
🔒 Locked

Calculating Matrix by Vector

Started by No_Germs Feb 17, 2005 at 3:53 PM 2 replies 350+ views
Original Post
No_Germs
No_Germs
suppose i have a normalized vector, and i want a matrix with one of its axes in the direction of the vector(i don't care where the other two axes will point to). how do i calculate the matrix?
Zakwayda
Zakwayda
I just answered this question in another post - here's what I wrote (slightly edited):

--------------------------------

What you need is an orthonormal basis. You want the direction vector to be one of these axes, let's say z. You can find the others by a) crossing z with an arbitrary vector to get an axis perpendicular to z, and b) crossing z and that vector to get the other vector. The only caveat is that an initial choice too close to z will produce a (more or less) null cross product. A nice workaround is to cross it with the axis it is most 'not aligned' with. Here's some code:

void Vector3::MakeOrthonormalBasis(Vector3& x, Vector3& y, Vector3& z, bool normalized) const{    // Find the principal axis most perpendicular to the vector    Vector3 axis;    if (fabsf(m_x) <= fabsf(m_y) && fabsf(m_x) <= fabsf(m_z))        axis.Set(1, 0, 0);    else if (fabsf(m_y) <= fabsf(m_x) && fabsf(m_y) <= fabsf(m_z))        axis.Set(0, 1, 0);    else        axis.Set(0, 0, 1);		    // Construct basis    z = *this;    if (!normalized)        z.Normalize();    z.Normalize();    x = z.UnitCross(axis);    y = z.Cross(x);}


(Note that this could actually be done a little more efficiently, but I'm not going to fix it right now.)
JohnBolton
JohnBolton
You are looking for how to implement a "look at" function. The technique is pretty simple:

You are looking for the basis vectors X, Y, and Z, given a vector V, to which Z is parallel.

Z = Normalize( V )
U = any unit vector != Z (usually it is the world's "up" vector)
X = Normalize( CrossProduct( U, Z ) )
Y = Cross( Z, X )

John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
No_Germs
No_Germs
it's all so simple now... Thanks a bunch :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.