I am programming on a LWJGL project and have been trying to figure out how to successfully use the GLU.gluUnProject function in order to transform a given point on the screen (mouse position) to world coordinates. I found several examples on Google and really tried hard to get it to work. I do manage to get a result vector but the values it gives me make no sense.
I initialize my scene using GL11.glFrustum(...) as follows:
public void initialize()
{
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glFrustum(-0.5, 0.5, -0.5, 0.5, 1.5, 6.5);
// left, right, bottom, top, zNear, zFar
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_REPLACE);
}
The window has a size of 800 x 600. Here is a screenshot:
Now to find a corresponding point in the game world for a given mouse position on the screen I use the following method:
public void calcWorldCoordinates(float mouseX, float mouseY)
// mouseX is in the range of [0..800] and mouseY in [0..600]
{
FloatBuffer model = BufferUtils.createFloatBuffer(16);
FloatBuffer projection = BufferUtils.createFloatBuffer(16);
IntBuffer viewport = BufferUtils.createIntBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, model);
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);
float viewportHeight = viewport.get(3); // = 600.0f
float y = viewportHeight - mouseY;
FloatBuffer posNear = BufferUtils.createFloatBuffer(16);
FloatBuffer posFar = BufferUtils.createFloatBuffer(16);
GLU.gluUnProject(mouseX, y, -1.5f, model, projection, viewport, posNear);
GLU.gluUnProject(mouseX, y, -6.5f, model, projection, viewport, posFar);
// ...
}
For mouseX = 300, mouseY = 400 I receive:
posNear = [x=-0.0580, y=0.0774, z=-0.6964]
posFar = [x=-0.0208, y=0.0278, z=-0.6964]
None of the three resulting coordinates makes sense to me. As far as I can tell x should be somewhere around 240 (each tile in the scene is of size 120 x 80 pixels). It should definitely be positive though and not -0.0580 or -0.0208.
I also looked at the model and projection matrix as well as the viewport size. Those are:
model:
1.0, 0.0, 0.0, 0.0
0.0, 1.0, 0.0, 0.0
0.0, 0.0, 1.0, 0.0
0.0, 0.0, 0.0, 1.0
projection:
3.0, 0.0, 0.0, 0.0
0.0, 3.0, 0.0, 0.0
0.0, 0.0, -1.6, -1.0
0.0, 0.0, -3.9, 0.0
viewport: 0, 0, 800, 600
I rewrote the code several times using different implementations of other people but could not get it to work. Maybe somebody could give me a hint. What I am doing wrong?