Search code examples
javainputlibgdxmouseeventmouseclick-event

Mouse click detection


I think i just need a little bit of correction on my code, but I can't figure out what im missing. Using input processor on Libgdx.

I want to add a new piece of food to an arraylist and draw it to the screen at the position of the mouse, but it does not draw.

here is my click detection:

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);
        }

here is the code that draws:

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

thanks for any help in advance!


Solution

  • I'm assuming Food class extends Sprite since you didn't put the code of Food and you are calling methods of the Sprite class

    • The screenY that touchDown method gives you starts from top to bottom, meaning 0 is at the top of the screen and Gdx.graphics.getHeight() is at bottom of the screen. You should invert the Y position since libgdx draws y-up and screenY is y-down so It should be.. foods.setPosition(screenX, Gdx.graphics.getHeight()-screenY);

    • Set the size of the sprite, I don't see you setting the size of the sprite, unless you have it set it up on the Food constructor you should set it. foods.setSize(10,10)

    • Does the touchDown method even fire when you click? if not you should set the input processor Gdx.input.setInputProcessor(this) in the create method
    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);
            }
    }