我有这个观点集:

glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective
glLoadIdentity(); //Reset the drawing perspective

我从鼠标点击中得到一个屏幕位置(sx,sy)。

给定z的值,如何从sx和sy计算3d空间中的x和y?

有帮助吗?

解决方案

您应该使用 gluUnProject

首先,计算“不投影”。到近处:

GLdouble modelMatrix[16];
GLdouble projMatrix[16];
GLint viewport[4];

glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);

GLdouble x, y, z;
gluUnProject(sx, viewport[1] + viewport[3] - sy, 0, modelMatrix, projMatrix, viewport, &x, &y, &z);

然后到远处飞机:

// replace the above gluUnProject call with
gluUnProject(sx, viewport[1] + viewport[3] - sy, 1, modelMatrix, projMatrix, viewport, &x, &y, &z);

现在,您在世界坐标中有一条线,可以找出您可能点击的所有可能点。所以现在你只需要插值:假设你给了z坐标:

GLfloat nearv[3], farv[3];  // already computed as above

if(nearv[2] == farv[2])     // this means we have no solutions
   return;

GLfloat t = (nearv[2] - z) / (nearv[2] - farv[2]);

// so here are the desired (x, y) coordinates
GLfloat x = nearv[0] + (farv[0] - nearv[0]) * t,
        y = nearv[1] + (farv[1] - nearv[1]) * t;

其他提示

最权威的来源 OpenGL的网站

一>

这实际上取决于投影矩阵,而不是模型视图矩阵。 http://www.toymaker.info/Games/html/picking.html应该帮助你 - 它以D3D为中心,但理论是一样的。

如果您正在寻找基于鼠标的选择,我建议使用选择渲染模式。

编辑:请注意,模型 - 视图矩阵确实发挥作用,但由于你的身份是一个非问题。

libqglviewer 有一个很好的选择框架,如果这就是你要找的东西

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top