Pregunta

So, I'm using LibGdx and trying to use their Rectangle class as a bounds for button pressing onn the touch screen. It works perfectly on a 1:1 scale, but when I put the game on my Phone (With a smaller screen) than the images get scaled and drawn properly, but the Rectangles don't. So I tried keeping my Rectangles at their normal scale, and "upscaling" the touch screen's XY Coords, but I guess I'm not doing that right, cause it doesn't work.

optionsMenu = new Vector<Rectangle>();
optionsMenu.add(new Rectangle(100 + (120 * 0), 100, 100, 100));
optionsMenu.add(new Rectangle(100 + (120 * 1), 100, 100, 100));
optionsMenu.add(new Rectangle(100 + (120 * 2), 100, 100, 100));
optionsMenu.add(new Rectangle(100 + (120 * 3), 100, 100, 100));

That's how i'm initalizing my bounding Rectangles.

This is how I'm initalizing my camera:

camera = new OrthographicCamera();
camera.setToOrtho(true, 800, 480);

This is how I'm drawing my buttons:

spriteBatch.draw(buttonImage, optionsMenu.get(2).bounds.getX(), 
optionsMenu.get(2).bounds.getY(), optionsMenu.get(2).bounds.getWidth(), 
optionsMenu.get(2).bounds.getHeight(), 0, 0, buttonImage.getWidth(), 
buttonImage.getHeight(), false, true);

And this is how I do my touch screen logic:

public boolean tap(float x, float y, int count, int button) {
    Vector3 temp = new Vector3(x, y, 0);
    camera.unproject(temp);

    float scalePos = (int) ((float) Gdx.graphics.getWidth()/800.0f);
    temp.x = temp.x * scalePos;
    temp.y = temp.y * scalePos;

    if(optionsMenu.get(0).bounds.contains(temp.x, temp.y)){
        //do sutff
    }

    else if(optionsMenu.get(1).bounds.contains(temp.x, temp.y)){
        //do other stuff

    }

  return false;
}
¿Fue útil?

Solución

A few days ago I ran into the same problem. This is what I did to solve it:

If you are using a viewport, then you should add that data to the camera.unproject call, to make sure that the viewport is being taken into account.

For example:

camera.unproject(lastTouch,viewport.x,viewport.y,viewport.width,viewport.height);

To debug the rectangle bounds and the touch position, I used this method to draw them into the screen:

private static ShapeRenderer debugShapeRenderer = new ShapeRenderer();

public static void showDebugBoundingBoxes(List<Rectangle> boundingBoxes) {
    debugShapeRenderer.begin(ShapeType.Line); // make sure to end the spritebatch before you call this line
    debugShapeRenderer.setColor(Color.BLUE);
    for (Rectangle rect : boundingBoxes) {
        debugShapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
    }
    debugShapeRenderer.end();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top