Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx get scaled touch position

Tags:

java

touch

libgdx

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: enter image description here

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

like image 447
Boldijar Paul Avatar asked Jan 25 '14 13:01

Boldijar Paul


2 Answers

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;
}
like image 80
Lestat Avatar answered Nov 06 '22 09:11

Lestat


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.

like image 8
TheLogicGuy Avatar answered Nov 06 '22 08:11

TheLogicGuy