【问题标题】:libgdx: Other coordinatesystem when using textureslibgdx:使用纹理时的其他坐标系
【发布时间】:2017-05-28 09:59:30
【问题描述】:

我有点困惑。我第一次使用 libgdx,坐标系有一些问题。当我创建纹理并想要设置位置时,我会这样做:

texture = new Texture("myGraphic.png", 0, 0); 

我的图片将位于左下角。

但是当我尝试通过以下方式获得触摸位置时:

 if(Gdx.input.isTouched())
    {
        Vector3 tmp = new Vector3(Gdx.input.getX(),Gdx.input.getY(),0);
        System.out.println("Coord:" + " + " + tmp.x + " + " + tmp.y);
    }

我发现 (0,0) 在左上角。 所以我在输出之前尝试了 camera.unproject(tmp),但是我只会得到 -1 和 1 之间的值。 如何为所有元素获得相同的坐标系?

【问题讨论】:

  • 显示您的代码如何使用相机?

标签: android libgdx touch textures coordinate-systems


【解决方案1】:

在 Libgdx 坐标系中,触摸是 y-down,但对于屏幕或图像,它是 y-up

看看LibGDXCoordinate systems

如果可以使用相机,则通过camera.setToOrtho(false);设置y轴向上,通过camera.unproject(vector3);方法获取世界点。

public class TouchSystem extends ApplicationAdapter {

    SpriteBatch batch;
    Texture texture;
    Vector3 vector3;
    OrthographicCamera camera;

    @Override
    public void create() {

        batch=new SpriteBatch();
        texture=new Texture("badlogic.jpg");
        vector3=new Vector3();
        camera=new OrthographicCamera();
        camera.setToOrtho(false);   // this will set screen resolution as viewport
    }

    @Override
    public void render() {

        Gdx.gl.glClearColor(0,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(texture,0,0);
        batch.end();

        if(Gdx.input.justTouched()) {

            vector3.set(Gdx.input.getX(),Gdx.input.getY(),0);
            camera.unproject(vector3);
            System.out.println("Coord:" + " + " + vector3.x + " + " + vector3.y);
        }
    }

    @Override
    public void dispose() {
        texture.dispose();
        batch.dispose();
    }
}

【讨论】:

  • 行得通!非常感谢你。另一个简短的问题:我是否必须使用 MainGame 类中的同一个相机,或者我可以在其他类中创建一个新相机(例如新屏幕)?
  • 相机不是重物,因此您可以在其他屏幕上创建不同的相机。
猜你喜欢
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
  • 2014-09-05
  • 2012-08-31
相关资源
最近更新 更多