我有以下为 LibGdx OpenGL 项目编写的 Java 类。无论您如何通过上下或两侧的上下左右调整大小,相机都会保持屏幕的纵横比。到目前为止,一切都很好。
当我尝试获取单击的鼠标 x、y 坐标并且该轴涉及信箱时,问题就出现了。首先是类:
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 坐标,我需要将这些原始坐标转换为我的相机的比例(虚拟高度和宽度)。
当屏幕被拉伸(完全没有信箱)时,很容易通过使用以下方法获得 x 和 y 坐标:
xRelative = (int) (x / (float)Gdx.graphics.getWidth() * Camera.getViewportWidth());
yRelative = (int) (y / (float)Gdx.graphics.getHeight() * Camera.getViewportHeight());
问题是当信箱发挥作用时,它会抛出该轴的坐标。我知道我需要考虑信箱的宽度,但我花了很长时间弄清楚如何计算它。
在上面我有“barSize = ????;” 我的第一直觉是这样做:barSize = physicalHeight - viewportHeight; // 例如使用高度
一旦我得到 barSize,我很确定我可以使用它来获得正确的数字(例如使用 y 轴):
yRelative = (int) (y / (float)Gdx.graphics.getHeight() * Camera.getViewportHeight() - Camera.getBarSize());
但数字不匹配。任何建议将不胜感激!