LibGDX 触摸位置坐标错误

3

我正在使用LibGdx,并尝试将他们的Rectangle类作为按钮在触摸屏上按下的边界。在1:1比例下它完美地工作,但是当我把游戏放到我的手机上(屏幕更小)时,图像被缩放和绘制正确,但矩形不会。所以我尝试保持我的矩形在它们正常的比例下,并“放大”触摸屏的XY坐标,但我猜我没有做对,因为它不起作用。

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));

这是我初始化边界矩形的方式。

这是我初始化相机的方式:

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

这是我绘制按钮的方法:

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);

这就是我如何处理触摸屏逻辑的方法:

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;
}

1
不确定是否是完整答案,但看到这一行代码"float scalePos = (int) ((float) Gdx.graphics.getWidth()/800.0f);",当getWidth() < 800时会发生什么?这将得到一个小于1.0f的数字,然后你将其强制转换为int类型,截断为零。 - R Hyde
对于按钮和UI界面,我建议您使用scene2d模块。 - rjurado01
1
为什么在反投影之后还要对位置进行缩放?你不应该这样做,因为反投影已经完成了这个转换。 - nEx.Software
1个回答

4

几天前我遇到了同样的问题,这是我解决它的方法:

如果您正在使用一个视口,则应将该数据添加到camera.unproject调用中,以确保视口被考虑在内。

例如:

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

为了调试矩形边界和触摸位置,我使用了以下方法将它们绘制到屏幕上:
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接