Rotating Towards Path?

Hi. I am having trouble on how to rotate an object in 3D space, based on the OpenGL rotate function glRotatef(…).

My object is traveling from one point to another in 3D space. I want my object to rotate in the direction it is traveling.

How would I find the angle, x, y, z that is needed for the glRotatef(…) function if I know the point where I am starting and the point where I am finishing.

You haven’t fully defined your problem. I assume you mean that you want your object to face the direction it is moving. There are infinitely many orientations your object can have doing that, because you haven’t defined what “up” for your object is. I’m going to assume you want your object’s “up” to be the same as it is in its unrotated definition. Here is a good link to lots of information about rotation matrices that you should study:

If you read through that link, you will notice that rotation in 3-space is typically defined by an axis of rotation and an angle (because that’s not ambiguous, unlike your definition). So, you need to find a way to define your problem in terms of an axis of rotation and the angle to rotate about it.

Given the assumptions I stated in the first paragraph that isn’t hard to do, provided you know the direction, without any rotations, your object faces. The direction your unrotated object faces defines a vector. The path your object is traveling also defines a vector. If you take the cross product of those two vectors, you obtain another vector, and it is perpendicular to the first two vectors (unless the first two vectors are collinear, in which case your object already is pointing in the correct direction). That perpendicular vector is your object’s desired axis of rotation. Your desired angle of rotation about that axis is the angle between the first two vectors. That’s all there is to it.

This question is related to the question: find the transform that rotates a vector into another vector. For a rotation transform you need an axis and angle, if your object is facing into direction d and you want it to face d’, you can find the axis as axis = cross(d, d’) and angle from the dot product dot(d, d’), if d and d’ are both unit vectors. No problem and no need for an up vector.

You can do the transform using a quaternion, an axis-angle matrix or some other way. If you use glRotatef() (a very bad idea, since GL does the rotation on the CPU, it is not hardware accelerated), then you will go the axis-angle way.