Libgdx中正确使用unProject

Libgdx中正确使用unProject

本文介绍了在Java Libgdx中正确使用unProject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a button clickable, but it isn't working - it seems like I need to use unproject() but I can't figure out how. The code in question is:

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();
        }
    }
}


推荐答案

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

In general you use camera.unproject(Vector) to transform your screen coordinates from a click or touch to your gameworld. This is needed because the origin is not necessarily the same and using the camera you can also zoom in and out, move around, rotate and so on. Unprojecting will take care of all of that and give you your game world coordinate matching the pointers position.

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

In your example it would go like this:

Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);

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

Having this said you should actually not do this UI task manually. Libgdx has also some shipped UI functionality which is called a Stage (see this). There are lots of widgets already available (see this). They use skins (you can get a basic one from here, you need all the uiskin.* files). They automatically forward inputevents to the socalled Actors, e.g. a button, and you just need to implement handling of those events.

这篇关于在Java Libgdx中正确使用unProject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!