开发者

OpenGL rotation in given direction

I'm thinking about an easy way of defining rotations in opengl. I understood how rotations about any given axis by some amount work. I also know that I can rotate around each axis in turn. But all that doesn't really help my problem. What I want to do, is rotating an object such that it 开发者_Python百科looks in a certain (given) direction. Thus i already know the result of a bunch of rotation.... how can I get there directly? Can I somehow define a lookAt direction for any object?


You don't have to use glRotate for this. You already figured out you know something, the target direction. But target direction is not everything, you could still rotate the object around the targeting axis, so you need an Up vector, too.

That is the object's local Z axis (or any other matrix you may designate as "forward"). You can normalize this vector and put it into the Z column of the objects transformation matrix.

The Up vector must be perpendicular to the target axis. Either you have one, or you derive one from the assumption, that the object's Up vector should at least go upwards, i.e. have a Y component. You can get a vector pointing up and perpendicular to the target axis, by taking the scalar product of the vector with the target axis and subtract from the target axis, the target axis vector scaled by the scalar product, then normalize. Let's say, Y is up:

U = normalize( T - T · Y )

Lastly you need the third local axis L. You can get this by taking the cross product of U and T, i.e.

L = U × T

Resulting from these you build a matrix

Lx  Ux  Tx  0
Ly  Uy  Ty  0
Lz  Uz  Tz  0
 0   0   0  1

and pass this to OpenGL using glMultMatrix (fixed function) or multiply it onto your own managed stack and supply it with glUniformMatrix (shaders).

Take note that glMultMatrix indexes matrix elements in the following order

0 4 8 c
1 5 9 d
2 6 a e
3 7 b f


I was finally able to solve my problem and it actually works pretty well. Thanks datenwolf!

//direction is the direction you want the object to point at
//up- first guess
Vector3f up;
if(abs(direction.x)< 0.00001 && abs(direction.z) < 0.00001){ //If x and z are really small
if(direction.y > 0)
    up = Vector(0.0, 0.0, -1.0); //if direction points in +y direction
else
    up = Vector(0.0, 0.0, 1.0); //if direction points in -y direction
} else {
    up = Vector(0.0, 1.0, 0.0); //y-axis is the general up direction
}

//left
Vector left = cross(direction,up);
left.normalize();

//final up
up= cross(left,direction);
up.normalize();

float matrix[]={left.x, left.y, left.z, 0.0f,     //LEFT
up.x, up.y, up.y, 0.0f,                       //UP 
direction.x, direction.y, direction.z, 0.0f,  //FORWARD
position.x, position.y, position.z, 1.0f};    //TRANSLATION TO WHERE THE OBJECT SHOULD BE PLACED
glMultMatrixf(matrix);
//DRAW OBJECT
//KEEP IN MIND the z-axis of your object points now in direction direction
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜