简体   繁体   中英

Libgdx get scaled touch position

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.

After 1-2 paintful hours I finnaly found the solution..

if (Gdx.input.isTouched()) {
        float x = Gdx.input.getX();
        float y = Gdx.input.getY();
        float yR = viewport.height / (y - viewport.y); // the y ratio
        y = 480 / yR;

        float xR = viewport.width / (x - viewport.x); // the x ratio
        x = 800 / xR;

        bubbles.add(new Bubble(x, 480 - y));

    }

Edit: this is an old deprecared way to do it, so don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM