Debe utilizar gluUnProject
:
En primer lugar, calcular el "unprojection" al plano cerca de:
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);
y luego al plano lejano:
// replace the above gluUnProject call with
gluUnProject(sx, viewport[1] + viewport[3] - sy, 1, modelMatrix, projMatrix, viewport, &x, &y, &z);
ahora que ha obtuvo una línea en coordenadas mundiales que rastrea todos los puntos posibles en los que podría haber estado haciendo clic en. Entonces ahora solo necesita interpolar: suponga que le dan la coordenada 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;
Perdón por el comentario novato. ¿El tercer parámetro en llamadas a gluUnproject es siempre el mismo (0 y 1) o depende de los valores zNear y zFar cuando estamos configurando la matriz de proyección con gluPerspective? – rgngl