鼠标单击检测

问题描述 投票:0回答:2

我想我只需要对我的代码进行一些更正,但是我无法弄清楚我缺少什么。在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();

感谢您的任何提前帮助!

java input libgdx mouseevent mouseclick-event
2个回答
0
投票

您的代码中有几个错误:

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

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


0
投票

我假设Food类为extends Sprite,因为您没有输入Food的代码,而您正在调用Sprite class的方法>

  • screenY方法给您的touchDown从上到下底部,意味着0在屏幕顶部,Gdx.graphics.getHeight()位于屏幕底部。由于libgdx绘制Y,并且y-upscreenY,因此应反转y-down位置,因此应该如此。foods.setPosition(screenX, Gdx.graphics.getHeight()-screenY);

  • 设置精灵的大小,除非您在Food构造函数中设置了精灵,否则您看不到它的大小。

  • 单击touchDown方法是否还会触发?如果不是,则应在Gdx.input.setInputProcessor(this)方法中设置输入处理器create
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);
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.