【发布时间】: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