Search code examples
opengllibgdxbox2dcoordinate-transformationprojection-matrix

Converting coordinates between 2 projection matrixes


I am writing a game using Java with LibGDX and Box2D libraries.

The screen contains 12*7 blocks, landscape, so I use orthographic camera with 12 and 7 as wiewport width and height. Also, Box2D world uses this camera. The window screen sizes are 840 by 490, to make them good to be divided by 12 and 7 :).

The camera is following the main character, so its projection matrix changes with every camera movement. So I use batch.setProjectionMatrix(camera.combined) and draw my game objects.

But what if I need to convert mouse screen coordinates to local box2D coordinates?
Is there a way to convert coordinates from one projection maxtrix to another?
For example, if my camera is looking at (0; 0), which is centered on the screen, I will get point in (840/2; 490/2) in the screen coordiates. And visa versa, from (420; 245) to ..whatever, considering the camera movement.


Solution

  • Have you tried unprojecting coordinates to you screen? This will convert the coordinates to world coordinates.

    Vector3 coordinates = new Vector3();    
    coordinates = new Vector3(x,y,0); //where x,y,0 is mouse coordinates
    Vector3 value = new Vector3();
    value = camera.unproject(coordinates);