簡體   English   中英

鼠標點擊檢測

[英]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();

提前感謝您的任何幫助!

我假設Foodextends Sprite因為您沒有放置Food的代碼並且您正在調用Sprite class方法

  • touchDown方法給你的screenY touchDown開始,意味着 0 在屏幕的頂部, Gdx.graphics.getHeight()在屏幕的底部。 您應該反轉Y位置,因為 libgdx 繪制y-up並且screenYy-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);
        }
}

您的代碼中有幾個錯誤:

  • 不要每次都創建新的紋理,創建一次。
  • 使用 button 參數來檢查它是否是左鍵。
  • 您需要從屏幕坐標轉換為您的世界坐標

對於最后一個,我建議您使用視口,然后您可以使用 viewport.unproject 方法轉換坐標。 您還必須在批次中使用視口相機矩陣才能使用相同的坐標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM