2
votes

Follow-up for: Calculating world coordinates from camera coordinates

I'm multiplying a 2D vector with a transformation matrix (OpenGL's model-view matrix) to get world coordinates from my camera coordinates.

I do this calculation like this:

private Vector2f toWorldCoordinates(Vector2f position) {

    glPushMatrix();
    glScalef(this.zoom, this.zoom, 1);
    glTranslatef(this.position.x, this.position.y, 0);
    glRotatef(ROTATION, 0, 0, 1);

    ByteBuffer m = ByteBuffer.allocateDirect(64);
    m.order(ByteOrder.nativeOrder());
    glGetFloatv(GL_MODELVIEW_MATRIX, m);

    float x = (position.x * m.getFloat(0)) + (position.y * m.getFloat(4)) + m.getFloat(12);
    float y = (position.x * m.getFloat(16)) + (position.y * m.getFloat(20)) + m.getFloat(28);

    glPopMatrix();
    return new Vector2f(x, y);
}

Now I also want to do this vice-versa: calculate the camera coordinates for a position in the world. How can I reverse this calculation?

1
If I'm reading this correctly, you only need to compute the inverse of your transformation matrix and apply that to your world coordinates.andand

1 Answers

2
votes

To create a matrix representing the inverse transform to the one above, apply the transforms in reverse, with negative quantities for the rotation and translation and an inverse quantity for the zoom:

glRotatef(-ROTATION, 0, 0, 1);
glTranslatef(-this.position.x, -this.position.y, 0);
glScalef(1.0f / this.zoom, 1.0f / this.zoom, 1);

Then multiply by the position vector as before.

The alternative is to compute the inverse matrix, but this way is much simpler.