title: opengl mouse coordinate to world coordinate
body: <p>I need to detect mouse motion and draw a ball at the mouse's position. I need the ball to be in world coordinate. So I'm trying to use <code>glUnProject</code> for this task and seems I'm not succeeding till now. This is my <code>motionFunc</code>:</p>
  
  <pre><code>void motionFunc( int x, int y)
  {
  
  
      GLint viewport[4];
      GLdouble modelview[16];
      GLdouble projection[16];
      GLfloat winX, winY, winZ;
      GLdouble posX, posY, posZ;
  
      glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
      glGetDoublev( GL_PROJECTION_MATRIX, projection );
      glGetIntegerv( GL_VIEWPORT, viewport );
  
      winX = (float)x;
      winY = (float)viewport[3] - (float)y;
      glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &amp;winZ );
  
      gluUnProject( winX, winY, winZ, modelview, projection, viewport, &amp;posX, &amp;posY, &amp;posZ);      //printf("winz: %f posz: %f\n",winZ,posZ);
      Ball.x=posX;
      Ball.y=posY;
      Ball.z=posZ;
      //printf("%f %f %f\n",Ball.x,Ball.y,posZ);
      glutPostRedisplay();
  }
  </code></pre>
  
  <p>now, I added a breakpoint on glutPostRedisplay. Turns out when I click-drag mouse, the Ball's coordinates(Ball.x,Ball.y,Ball.z) are something like: </p>
  
  <pre><code>(Ball).x -727.175354
  (Ball).y 407.310242
  (Ball).z -865.000610
  </code></pre>
  
  <p>why is the z coordinate so far? My camera is at z=+135. And other objects in my model are like, at z= -3 to +3. I need the ball's z coordinate to be in the same range. </p>
  
  <p>now, what exactly is <code>winZ</code>? Here, I checked it always turns out to be 1.00. I tried to hardcode <code>winZ</code> and I found at <code>winZ=0.85</code>, the ball seems like to be always under the mouse(I can drag the ball with my mouse and the ball is always under the pointer). But then the Ball's coordinates are like:</p>
  
  <pre><code>(Ball).x -4.67813921
  (Ball).y 2.57806134
  (Ball).z 128.370895
  </code></pre>
  
  <p>which is so close to the camera but x and y coordinates are not good for me. they always come out to be near the origin. which is not what I want. My other objects' x and y coordinates have a wider range. </p>
  
  <p>Finally, my question is, what is the correct way to do <code>glUnproject</code> or something of the same sort?</p>