Search code examples
javaandroidlibgdx

How do I get a touch coordinates in LibGdx using the same resolution in al devices?


So I was using this code to get the coordinates of the touch in the screen.

 if(Gdx.input.justTouched()){
            System.out.println("X= "+Gdx.input.getX()+"Y= "+Gdx.input.getY());
        }

but if I have a device with a 1280x960 resolution and I have a 800x600 orthographic camera.

What can I do to obtain the coordinates inside the camera instead the device touch coordinates

"for example if I touch the limit of the screen on the x axis I want to get 800 instead of 1280"


Solution

  • The correct way to do it is to use the camera to give you the world coordinates from the screen coordinates.

    For example...

        Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY());
        camera.unproject(mousePos); // mousePos is now in world coordinates
    

    That way, if you change the camera (zoom / rotate / whatever) then everything will still work.

    If you're using a Viewport, then you should use the vieport's unproject method instead, as it may have additional issues to handle (e.g. allowing for the letterboxing in a FitViewport).

    Note - In the example I gave, it'd be better to reuse a single Vector3 instance but I wanted the example to be as simple as possible.