在 3D 中查找 X、Y 和 Z 轴的角度 - OpenGL/C++ [英] Finding the angles for the X, Y and Z axis in 3D - OpenGL/C++
问题描述
我目前正在尝试使用 OpenGL(使用 SDL)将一个立方体绘制到我在屏幕中左键单击的位置,然后让它指向屏幕中我右键单击的位置.
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.
我可以使用 gluUnproject 在我想要的位置成功绘制一个立方体 - 这意味着我已经知道我的立方体所在的坐标.
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.
当然我还是用gluUnproject来求我右键的坐标,但是我只知道怎么用二维图形绕Z轴旋转.
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.
例如之前,如果我想在 2D 中围绕 Z 轴旋转一个四边形(当然,这将是一个自上而下的视图,其中 Z 轴仍然穿过"屏幕),我会执行以下操作:
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);
我的问题是,我将如何在 3D 中执行此操作?
My question is, how would I go about doing this in 3D?
- 我是否需要像上面那样计算每个轴的角度?
- 如果是这样,我该如何计算绕 X 轴和 Y 轴旋转的角度?
- 如果没有,我应该使用什么方法来达到我想要的结果?
非常感谢任何帮助.
推荐答案
如果你的立方体在 A = (x0,y0,z0)
If your cube is at A = (x0,y0,z0)
如果您的立方体当前正在查看 B=(x1,y1,z1)
If your cube is currently looking at B=(x1,y1,z1)
如果你想让它看看 C=(x2,y2,z2) 那么;
and if you want it to look at C=(x2,y2,z2) then;
设 v1 为从 A 到 B 的向量
let v1 be the vector from A to B
v1 = B - A
并且 v2 是从 A 到 C 的那个
and v2 be the one from A to C
v2 = C - A
首先将它们标准化.
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
您可以使用
glRotate(angle, axis[0], axis[1], axis[2])
这篇关于在 3D 中查找 X、Y 和 Z 轴的角度 - OpenGL/C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!