我想让一个按钮可点击,但它不起作用 - 似乎我需要使用 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();
}
}
}
最佳答案
通常,您使用 camera.unproject(Vector)
将您的屏幕坐标从点击或触摸转换到您的游戏世界。这是必需的,因为原点不一定相同,并且使用相机还可以放大和缩小、四处移动、旋转等。 Unprojecting 将处理所有这些,并为您提供与指针位置匹配的游戏世界坐标。
在你的例子中它会是这样的:
Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
话虽如此,您实际上不应该手动执行此 UI 任务。 Libgdx 也有一些被称为 Stage
的 UI 功能(参见 this )。已经有很多小部件可用(参见 this )。他们使用皮肤(你可以从 here 得到一个基本的皮肤,你需要所有的 uiskin.* 文件)。它们自动将输入事件转发给所谓的 Actor
,例如一个按钮,您只需要实现对这些事件的处理。
关于java - 在 Java Libgdx 中正确使用 unProject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18554126/