OpenGL:将鼠标点击投影到几何体上

9

我有一个这样的视图设置:

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

我从鼠标点击中获得了屏幕位置(sx,sy)。

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

1个回答

11
你应该使用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;

抱歉,我的评论可能有点菜。在gluUnproject调用中,第三个参数始终相同(0和1),还是取决于我们使用gluPerspective设置投影矩阵时的zNear和zFar值? - rgngl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接