[英]Mouse click detection
我想我只需要對我的代碼進行一些更正,但我無法弄清楚我缺少什么。 在 Libgdx 上使用輸入處理器。
我想在一個數組列表中添加一塊新食物並在鼠標所在的位置將其繪制到屏幕上,但它沒有繪制。
這是我的點擊檢測:
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();
提前感謝您的任何幫助!
我假設Food
類extends
Sprite
因為您沒有放置Food
的代碼並且您正在調用Sprite
class
方法
touchDown
方法給你的screenY
touchDown
開始,意味着 0 在屏幕的頂部, Gdx.graphics.getHeight()
在屏幕的底部。 您應該反轉Y
位置,因為 libgdx 繪制y-up
並且screenY
是y-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);
}
}
您的代碼中有幾個錯誤:
對於最后一個,我建議您使用視口,然后您可以使用 viewport.unproject 方法轉換坐標。 您還必須在批次中使用視口相機矩陣才能使用相同的坐標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.