Screen to 3D World Coords (again)

Started by
1 comment, last by X Abstract X 14 years, 6 months ago
I can't seem to figure out how to convert from screen coordinates to 3D world coordinates. I'm working in JOGL and this is my code currently. It simply does not work. I would really appreciate if someone could help.

public Vector screenToWorld(int screenX, int screenY) {
		double world[] = new double[3]; //store world coordinates here
		int viewport[] = new int[4];
		double modelview[] = new double[16];
		double projection[] = new double[16];
		
		gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0);
		gl.glGetDoublev(GL.GL_MODELVIEW_MATRIX, modelview, 0);
		gl.glGetDoublev(GL.GL_PROJECTION_MATRIX, projection, 0);
		
		glu.gluUnProject(screenX, screenY, gl.GL_DEPTH_COMPONENT, modelview, 0, projection, 0, viewport, 0, world, 0);
		
		return(new Vector((float)world[0], (float)world[1], (float)world[2]));
}

Advertisement
You are missing a step. GL_DEPTH_COMPONENT does not mean the depth itself, but is a flag for glReadPixels to obtain the depth, which can be different at every pixel.
You should be able to get the depth as follows:
float[] depth = new float[1];gl.glReadPixels(screenX, screenY, 1, 1, gl.GL_DEPTH_COMPONENT, GL_FLOAT, depth);


Then you pass depth[0] as the z-component to gluUnProject.
Thanks again!

This topic is closed to new replies.

Advertisement