vinczemarton
vinczemarton

Reputation: 8156

Rotation to a given direction in opengl

I'm starting to confuse math.

I want to make a rotation that translates the direction of the y axis to a given direction.

So I want to make a function that has a direction for input, and makes a call to glRotatef(). After the function anything I draw should point to the given direction instead of upwards.

glRotatef has 4 parameters: angle, x, y, z

Upvotes: 3

Views: 3927

Answers (1)

mrucci
mrucci

Reputation: 4470

Basically, you want to align the world y axis with a (unit-length) direction d. In order to compose a rotation matrix with glRotatef, you need an axis a = [a_x, a_y, a_z] and an angle omega.

The rotation axis that takes y into d is perpendicular to both y and d, thus can be computed via the vector cross product:

a = cross(y, d);

the angle of rotation omega is simply the angle between the vectors y and d, thus can be computed from the dot product:

omega = acos(dot(y, d));

Now you can build your rotation matrix with:

glRotatef(omega, a_x, a_y, a_z);

Be careful that omega needs to be in degrees and not radians. Also check the direction of rotation.

Upvotes: 2

Related Questions