Hi!
I am making a RTS game with OpenGL 2 and I am at the point where I am only adding in game mechanics. As any RTS game will likely need this, I am trying to implement mouse picking from the screen coordinates to the world coordinates. I tried many different solutions with view and projection matrices using matrix math, and I couldnt get it to work, and then I found gluUnProject, and so far, that has been the closest to working. It follows the mouse mostly except for one small thing: the coordinates are slightly off. So far, the only things I have done to the camera that could cause this is that I rotated the camera itself 45 degrees on the X axis so that I have a 3D isometrical-type view of the map. When I try offsetting the model by about positive 30, it seems to stay with the mouse until I get near the edge of the screen, and that is where it starts going too far positive. I am currently using the Win32 API for my display, so I am not completely sure if that could have an effect on it.
I have spent a lot of time working on this, and I was just wondering if anyone here could help me out with my issue.
Here is my mouse cursor code (it is a modified version of the NEHE mousepicking code):
Vector3 GetOGLPos(double mvmatrix[16], double projmatrix[16], int viewPort[4], HWND hWnd)
{
//GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
GetCursorPos(&p); // Gets The Current Cursor Coordinates (Mouse Coordinates)
ScreenToClient(hWnd, &p);
glDisable(GL_DEPTH_TEST);
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewPort);
winX = (float)p.x;
winY = (float)viewPort[3] - (float)p.y;
//glReadPixels(winX, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, 0.0, modelview, projection, viewPort, &posX, &posY, &posZ);
gluUnProject(winX, winY, 1.0, modelview, projection, viewPort, &posX, &posY, &posZ);
glEnable(GL_DEPTH_TEST);
return Vector3(posX, posY, posZ);
}
Keep in mind that variable p is a point that represents the mouse cursor position. It supports both an X and a Y value. p.x is the mouse's X coordinates and p.y is the mouse's Y coordinates.
Thank y'all in advance!
-Ryan