我想我只需要对我的代码进行一些更正,但是我无法弄清楚我缺少什么。在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();
感谢您的任何提前帮助!
您的代码中有几个错误:
对于最后一个,我建议您使用viewport,然后可以使用viewport.unproject方法转换坐标。您还必须在批次中使用视口相机矩阵,才能使用相同的坐标。
我假设Food
类为extends
Sprite
,因为您没有输入Food
的代码,而您正在调用Sprite
class
的方法>
screenY
方法给您的touchDown
从上到下底部,意味着0在屏幕顶部,Gdx.graphics.getHeight()
位于屏幕底部。由于libgdx绘制Y
,并且y-up
为screenY
,因此应反转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);
}
}