0

我正在使用带有LibGDXBox2D库 的Java编写游戏。

屏幕包含 12*7 块,横向,所以我使用 12 和 7 作为 wiewport 宽度和高度的正交相机。此外,Box2D世界使用此相机。窗口屏幕尺寸为 840 x 490,以便将它们除以 12 和 7 :)。

摄像机跟随主角,所以它的投影矩阵随着摄像机的每次移动而变化。所以我使用batch.setProjectionMatrix(camera.combined)并绘制我的游戏对象。

但是,如果我需要将鼠标屏幕坐标转换为本地 box2D 坐标怎么办?
有没有办法将坐标从一个投影 maxtrix 转换为另一个?
例如,如果我的相机正在注视屏幕中央的 (0; 0),我将在屏幕坐标中找到 (840/2; 490/2) 的点。反之亦然,从 (420; 245) 到 ..whatever,考虑到相机的移动。

4

2 回答 2

1

您是否尝试过将坐标投影到屏幕上?这会将坐标转换为世界坐标。

Vector3 coordinates = new Vector3();    
coordinates = new Vector3(x,y,0); //where x,y,0 is mouse coordinates
Vector3 value = new Vector3();
value = camera.unproject(coordinates);
于 2014-10-27T07:41:12.967 回答
0

如果有人感兴趣,这就是我解决本地到屏幕坐标转换问题的方法。在这个例子中,我的相机跟随主角,我想hero使用camera.

static final float WIDTH = 640;
static final float HEIGHT = 480;
static final float METERS_TO_PIXELS = 40; //or whatever 

//first we create a vector from the camera position to the object
Vector2 relative = new Vector2(hero.getPosition().x, hero.getPosition().y);
relative.sub(camera.position.x, camera.position.y);

//now scale the relative vector to screen coordinates
Vector2 result = new Vector2(WIDTH/2.0f + relative.x / METERS_TO_PIXELS * WIDTH,
                             HEIGHT/2.0f + relative.y / METERS_TO_PIXELS * HEIGHT); 
于 2014-10-28T14:23:27.687 回答