寻找角度的X,在3D Y和Z轴 - 的OpenGL / C ++角度、OpenGL

2023-09-08 00:48:09 作者:?.blue friend(蓝朋友)

我目前正在使用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.

例如之前,如果我想绕Z轴四(当然,这将是一个俯视图,其中的Z轴仍然是经历的画面)在2D我会做这样的事情:

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轴旋转? 如果不是,我应该用什么方法来达到我预期的效果?

任何帮助是极大的AP preciated。

Any help is greatly appreciated.

推荐答案

如果您的多维数据集是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

v1 = B - A

和V2是一个从A到C

and v2 be the one from A to C

V2 = C - A

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与

You can call glRotate with

glRotate(angle, axis[0], axis[1], axis[2])