views:

1079

answers:

5

Given a point such as (0, 0, 0) and a vector like (x, y, z). What is the easiest way to align the negative Z-axis centered at (0, 0, 0) to point in the direction of this vector? Examples using OpenGL would be welcome, but not neccessary.

+1  A: 

To answer my own question, the best answer I've come up with is this:

Divide the vector up into "components". The x component is the displacement along the x axis. If we turn to trigonometry, we have that cos(alpha) = vector_magnitude / x. If we compute the RHS then we can derive alpha, which is the amount by which we'd have to rotate around the y axis.

Then the coordinate system can be aligned to the vector by a series of calls to glRotatef()

fluffels
+3  A: 

There's lots of different ways to rotate a coordinate-frame to point in a given direction; they'll all leave the z-axis pointed in the direction you want, but with variations in how the x- and y-axes are oriented.

The following gets you the shortest rotation, which may or may not be what you want.

vec3 target_dir = normalise( vector );
float rot_angle = acos( dot_product(target_dir,z_axis) );
if( fabs(rot_angle) > a_very_small_number )
{
    vec3 rot_axis = normalise( cross_product(target_dir,z_axis) );
    glRotatef( rot_angle, rot_axis.x, rot_axis.y, rot_axis.z );
}
A: 

There are lots of resources out there about rotating your coordinates (or rotating objects, which amounts to the same thing). I learnt a lot from this site, both about how to program in multiple dimensions and especially how to manipulate vectors

Simon
A: 

The page here has a section "Transformations for moving a vector to the z-axis" that seems to be what you want, or perhaps the inverse of it.

Glenn
A: 

You probably want to have a look at Diana Gruber's article

bobobobo