0

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.

genpfault
  • 51,148
  • 11
  • 85
  • 139

2 Answers2

1

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);
islander_zero
  • 3,342
  • 3
  • 12
  • 17
0

If anyone is interested, this is how I solved the problem with a local-to-screen coordinates convertion. In this example my camera is following the main character, and I want to get position of the object hero using the camera.

static final float WIDTH = 640;
static final float HEIGHT = 480;
static final float METERS_TO_PIXELS = 40; //or whatever 

//first we create a vector from the camera position to the object
Vector2 relative = new Vector2(hero.getPosition().x, hero.getPosition().y);
relative.sub(camera.position.x, camera.position.y);

//now scale the relative vector to screen coordinates
Vector2 result = new Vector2(WIDTH/2.0f + relative.x / METERS_TO_PIXELS * WIDTH,
                             HEIGHT/2.0f + relative.y / METERS_TO_PIXELS * HEIGHT);