鼠标点击检测

Mouse click detection

我想我只需要对我的代码进行一些更正,但我不知道我遗漏了什么。在 Libgdx.

上使用输入处理器

我想在一个arraylist中添加一个新的食物,然后在鼠标所在的位置绘制到屏幕上,但是没有绘制。

这是我的点击检测:

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
            Food foods;
            foods = new Food(new Sprite(new Texture("FlakeFood.gif")));      //sprite
            foods.setPosition(screenX, screenY);
            food.add(foods);
        }

这里是绘制的代码:

batch.begin();
for (int i = 0; i < food.size(); i++) {
            food.get(i).draw(batch);
        }
batch.end();

提前感谢您的帮助!

您的代码中有几个错误:

  • 不要每次都创建新的Texture,创建一次。
  • 使用按钮参数来检查它是否是左按钮。
  • 您需要将屏幕坐标转换为您的世界坐标

对于最后一个,我建议您使用viewport,然后您可以使用viewport.unproject 方法转换坐标。您还必须在批次中使用视口相机矩阵才能使用相同的坐标。

我假设 Food class extends Sprite 因为你没有输入 Food 的代码并且你正在调用Spriteclass

  • touchDown方法给你的screenY从上到下 bottom,表示 0 位于屏幕顶部, Gdx.graphics.getHeight() 在屏幕底部。你应该反转 Y 的位置,因为 libgdx 绘制 y-upscreenYy-down 所以它应该是.. foods.setPosition(screenX, Gdx.graphics.getHeight()-screenY);

  • 设置精灵的大小,我没看到你设置精灵的大小,除非你在 Food 构造函数上设置它,你应该设置它。 foods.setSize(10,10)

  • touchDown 方法是否在您单击时触发?如果不是,您应该在 create 方法
  • 中设置输入处理器 Gdx.input.setInputProcessor(this)
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println("Does this even run? if not, set the input processor Gdx.input.setInputProcessor(this) in the create method");
        if(button == Input.Buttons.LEFT){
            Food foods = new Food(new Sprite(flakeFoodTexture));
            foods.setPosition(screenX, Gdx.graphics.getHeight()- screenY);// invert the Y position
            foods.setSize(10,10);// set the size
            food.add(foods);
        }
}