I am currently trying to use OpenGL (With SDL) to draw a cube to the location where I left click in the screen and then get it to point at the position in the screen where I right click.
I can successfully draw a cube at my desired location using gluUnproject - Meaning I already know the coordinates of which my cube is situated.
However I do not know how to calculate all of the angles required to make my cube point at the new location.
Of course I am still using gluUnproject to find the coordinates of my right click, but I only know how to rotate around the Z axis from using 2D graphics.
For example before, if I wanted to rotate a quad around the Z axis (Of course, this would be a top down view where the Z axis is still "going through" the screen) in 2D I would do something like:
angle = atan2(mouseCoordsY - quadPosY, mouseCoordsX - quadPosX);
glRotatef(angle*180/PI, 0, 0, 1);
My question is, how would I go about doing this in 3D?
Any help is greatly appreciated.
If your cube is at A = (x0,y0,z0)
If your cube is currently looking at B=(x1,y1,z1)
and if you want it to look at C=(x2,y2,z2) then;
let v1 be the vector from A to B
v1 = B - A
and v2 be the one from A to C
v2 = C - A
First normalize them.
v1 = v1 / |v1|
v2 = v2 / |v2|
then calculate the rotation angle and the rotation axis as
angle = acos(v1*v2) //dot product
axis = v1 X v2 //cross product
You can call glRotate with
glRotate(angle, axis[0], axis[1], axis[2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With