我有一个我为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());
但这些数字并不匹配。任何建议都会非常感激!
答案 0 :(得分:3)
Ray ray = camera.getPickRay(x, y);
System.out.println(ray.origin.x);
System.out.println(ray.origin.y);