Hello all
I am trying to create a simple ray trace function whereby I can draw a 3D line that goes from the character to the point in space that the mouse is over. I am using the following code taken off this Nehe’s tutorial :
Vector3 World::projectedMouse(float mx, float my){
GLdouble model_view[16];
GLint viewport[4];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble dx, dy, dz;
glGetDoublev(GL_MODELVIEW_MATRIX, model_view);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)mx;
winY = (float)viewport[3] - (float)my;
glReadPixels ((int)mx, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, model_view, projection, viewport, &dx, &dy, &dz);
Vector3 pr = Vector3(dy, dy, dz);
glColor3f(1,0,0);
glBegin (GL_LINE_LOOP);
glVertex3f(player->getPosition().x, player->getPosition().y + 100, player->getPosition().z); // 0
glVertex3f(pr.x,pr.y,pr.z); // 1
glVertex3f(player->getPosition().x, player->getPosition().y, player->getPosition().z); // 0
glEnd();
return pr;
}
And I draw a line from the player position to the unprojected point but the results I get are really not accurate, the point in space rarely corresponds to where the mouse lies, most of the time it is some random spot in space. Here’s a screen with the grey line that goes from the character to the sky when the mouse was simply over the character’s head:
Am I doing something wrong in that function? Am I not doing something? Or is there a specific location in the Opengl code where that should be placed?
Thank you in advance!