# Is it really that I can't get a correct 3D coordinate from 2D screen?

I wish to convert 2D screen coordinate to 3D(code below). But the Z value converted always can’t control well. It’s often worry.
How can I do?

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX=(float)mouse_x;
winY=(float)viewport-(float)mouse_y;
int(winY),
1,1,
GL_DEPTH_COMPONENT,
GL_FLOAT,
&winZ);
gluUnProject((GLdouble)winX,(GLdouble)winY,(GLdouble)winZ,modelview,projection,viewport,&object_x,&object_y,&object_z);

I see nothing wrong with your code. Of course, you might get some numerical errors, floating point math can never be exact.

Perhaps the modelview matrix at the time your code gets executed is not the same as the one used when drawing…

Btw. I don’t think this is an advanced question But I can’t get the correct 3D coordinate. The x,y and z, especially z, are worry with these codes. It is difficultly to control the Z value.

I have the same problem and I can not get the z coordinate from the z buffer. Please, somebody help us

Well, these difficulties may be connected to internal conversion of depth values. Remember that if you have set near and far depth with glDepthRange(n, f) or if your are using default values n = 0 and f = 1, the depth is converted according to the following formula:
zw = ((f-n)/2) * z + (f+n)/2;
Therfore, in the most simple case you just get your depth value divided by 2 before actually being written to the depth buffer (remember that after projection the depth value is between -1 and 1). I’ve had a problem with this once; so, you could just transform the value back (that is, multiply by 2 and subtract 1 in the simplest case) to get the value you think is correct.

The y coordinate should actually be
newY = height - y - 1

Secondly, the depth coordinates are not part of a linear scale. The closer the depth is to the near clipping plane, the better the accuracy. The farther it is, the more likely you are to run into issues. Make sure your near and far clipping planes are only as far apart as you need them to be, otherwise you are introducing greater error.