【问题标题】:LibGDX touch position coords errorLibGDX 触摸位置坐标错误
【发布时间】:2013-06-14 00:13:22
【问题描述】:

所以,我正在使用 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;
}

【问题讨论】:

  • 不确定这是否是完整的答案,但是查看“float scalePos = (int) ((float) Gdx.graphics.getWidth()/800.0f);”这一行,getWidth 时会发生什么()
  • 对于一般的按钮和 UI,我建议您使用 scene2d 模块。
  • 取消投影后为什么要缩放位置?您不应该这样做,因为 unproject 已经进行了该转换。

标签: java android touch libgdx coordinate-transformation


【解决方案1】:

几天前我遇到了同样的问题。这是我为解决它所做的:

如果您正在使用视口,则应将该数据添加到 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多