我有这个视图集:
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;