我为 LibGdx OpenGL 项目编写了以下 Java 类。 无论您如何通过顶部、底部或侧面的信箱调整屏幕大小,相机都会保持屏幕的宽高比。到目前为止,一切顺利。
当我尝试获取鼠标单击的 x、y 坐标,并且该轴涉及信箱时,就会出现问题。 首先是类(class):
public class Camera {
private static float viewportWidth;
private static float viewportHeight;
private static float aspectRatio;
private static float barSize;
/**
* Creates an orthographic camera where the "play area" has the given viewport size. The viewport will be scaled to maintain the aspect ratio.
*
* @param virtualWidth the width of the game screen in virtual pixels.
* @param virtualHeight the height of the game screen in virtual pixels.
* @return the new camera.
*
*/
public static OrthographicCamera createCamera(float virtualWidth, float virtualHeight) {
aspectRatio = virtualWidth / virtualHeight;
float physicalWidth = Gdx.graphics.getWidth();
float physicalHeight = Gdx.graphics.getHeight();
if (physicalWidth / physicalHeight >= aspectRatio) {
// Letterbox left and right.
viewportHeight = virtualHeight;
viewportWidth = viewportHeight * physicalWidth / physicalHeight;
barSize = ????;
}
else {
// Letterbox above and below.
viewportWidth = virtualWidth;
viewportHeight = viewportWidth * physicalHeight / physicalWidth;
barSize = ????;
}
OrthographicCamera cam = new OrthographicCamera(viewportWidth , viewportHeight);
cam.position.set(virtualWidth / 2, virtualHeight / 2, 0);
cam.rotate(180, 1, 0, 0);
cam.update();
Gdx.app.log("BTLog", "barSize:"+barSize);
return cam;
}
public static float getViewportWidth() {
return viewportWidth;
}
public static float getViewportHeight() {
return viewportHeight;
}
}
当事件发生时,LibGdx 为我提供 x 和 y 坐标,我需要将这些原始坐标转换为相机的比例(虚拟高度和宽度)。
当屏幕被拉伸(stretch)时(根本没有信箱),可以很容易地使用以下方法获取 x 和 y 坐标:
xRelative = (int) (x / (float)Gdx.graphics.getWidth() * Camera.getViewportWidth());
yRelative = (int) (y / (float)Gdx.graphics.getHeight() * Camera.getViewportHeight());
问题是当信箱发挥作用时,它会偏离该轴的坐标。我知道我需要考虑信箱的宽度,但我花了很长时间才弄清楚如何计算它。
上面有“barSize = ??????;”我的第一直觉是这样做: barSize = 物理高度 - 视口(viewport)高度;//以高度为例
一旦我得到了 barSize,我相当确定我可以使用它来获得正确的数字(例如使用 y 轴):
yRelative = (int) (y / (float)Gdx.graphics.getHeight() * Camera.getViewportHeight() - Camera.getBarSize());
但是数字不匹配。任何建议将不胜感激!
最佳答案
Ray ray = camera.getPickRay(x, y);
System.out.println(ray.origin.x);
System.out.println(ray.origin.y);
关于java - 我如何计算这个类的信箱大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5761674/