转换2个投影矩阵之间的坐标

时间:2014-10-27 07:25:33

标签: opengl libgdx box2d coordinate-transformation projection-matrix

我正在使用 Java LibGDX Box2D 库编写游戏。

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

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

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);