I'm working at a android game using LIBGDX.
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
Here, the x and y returns the position of the touch of the device screen, and the values are between 0 and the device screen width and height.
My game resolution is 800x480, and it will keep its aspect ratio on every device. I want to find out a way to get the touch position, related to the game rectangle, this image can explain exactly:
Is there a way to do it? I want to get the touch position related to my viewport.. I use this to keep the aspect ratio http://www.java-gaming.org/index.php?topic=25685.0
Unproject your touch.
Make a Vector3 object for user touch:
Vector3 touch = new Vector3();
And use the camera to convert the screen touch coordinates, to camera coordinates:
@Override
public boolean touchDown(int x, int y, int pointer, int button){
camera.unproject(touch.set(x, y, 0)); //<---
//use touch.x and touch.y as your new touch point
return false;
}
In the newer version of LibGDX you can achieve it with the built in viewports.
Firstly choose your preferred viewport the one you want here is FitViewport.
You can read about them here:
https://github.com/libgdx/libgdx/wiki/Viewports
Next, you declare and initialize the viewport and pass your resolution and camera:
viewport = new FitViewport(800, 480, cam);
Then edit your "resize" method of the screen class to be like that:
@Override
public void resize(int width, int height) {
viewport.update(width, height);
}
Now wherever you want to get touch points you need to transfer them to new points according to the new resolution. Fortunately, the viewport class does it automatically.
Just write this:
Vector2 newPoints = new Vector2(x,y);
newPoints = game.mmScreen.viewport.unproject(newPoints);
Where x and y are the touch points on the screen and in the second line "newPoints" gets the transformed coordinates.
Now you can pass them wherever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With