在Java Libgdx中正确使用unProject

Chi*_*nse 13 java opengl libgdx

我想点击一个按钮,但它不起作用 - 似乎我需要使用,unproject()但我无法弄清楚如何.有问题的代码是:

Texture playButtonImage;
SpriteBatch batch;
ClickListener clickListener;
Rectangle playButtonRectangle;
Vector2 touchPos;
OrthographicCamera camera;

@Override
public void show() {
    playButtonImage = new Texture(Gdx.files.internal("PlayButton.png"));

    camera = new OrthographicCamera();
    camera.setToOrtho(false, 800, 480);
    batch = new SpriteBatch();

    playButtonRectangle = new Rectangle();
    playButtonRectangle.x = 400;
    playButtonRectangle.y = 250;
    playButtonRectangle.width = 128;
    playButtonRectangle.height = 64;
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0.2f, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();
    batch.setProjectionMatrix(camera.combined);

    batch.begin();
    batch.draw(playButtonImage, playButtonRectangle.x, playButtonRectangle.y);
    batch.end();

    if (Gdx.input.isTouched()) {
        Vector2 touchPos = new Vector2();
        touchPos.set(Gdx.input.getX(), Gdx.input.getY());


        if (playButtonRectangle.contains(touchPos)) {
            batch.begin();
            batch.draw(playButtonImage, 1, 1);
            batch.end();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

noo*_*one 12

通常,您可以使用camera.unproject(Vector)点击或触摸将屏幕坐标转换为游戏世界.这是必需的,因为原点不一定相同,使用相机你也可以放大,移动,旋转等等.Unprojecting会处理所有这些并为您提供与指针位置匹配的游戏世界坐标.

在您的示例中,它将如下所示:

Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
Run Code Online (Sandbox Code Playgroud)

有了这个说你实际上不应该手动执行这个UI任务.Libgdx还提供了一些称为a的UI功能Stage(参见本文).已经有很多小部件可用(见这个).他们使用皮肤(你可以从这里得到一个基本的,你需要所有的uiskin.*文件).它们会自动将inputevents转发给所谓Actors的按钮,例如按钮,您只需要实现对这些事件的处理.

  • 正如我的回答所述,触摸时在每个帧上初始化一个新的Vector3对象会引入大量开销.GC循环很重,特别是在游戏等时间关键应用上(在移动设备上更糟糕;而且libgdx也是为移动设备而构建的) (2认同)