Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx Mouse just clicked

Tags:

java

libgdx

I'm trying to get when the mouse just clicked, not when the mouse is pressed. I mean I use a code in a loop and if I detect if the mouse is pressed the code will execute a lot of time, but I want execute the code only Once, when the mouse has just clicked.

This is my code :

if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){

            //Some stuff
}
like image 546
LeSam Avatar asked Jul 14 '13 22:07

LeSam


3 Answers

See http://code.google.com/p/libgdx/wiki/InputEvent - you need to handle input events instead of polling, by extending InputProcessor and passing your custom input processor to Gdx.input.setInputProcessor().

EDIT:

public class MyInputProcessor implements InputProcessor {
   @Override
   public boolean touchDown (int x, int y, int pointer, int button) {
      if (button == Input.Buttons.LEFT) {
          // Some stuff
          return true;     
      }
      return false;
   }
}

And wherever you want to use that:

MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);

If find it easier to use this pattern:

class AwesomeGameClass {
    public void init() {
        Gdx.input.setInputProcessor(new InputProcessor() {
            @Override
            public boolean TouchDown(int x, int y, int pointer, int button) {
                if (button == Input.Buttons.LEFT) {
                    onMouseDown();
                    return true;
                }
                return false
            }

            ... the other implementations for InputProcessor go here, if you're using Eclipse or Intellij they'll add them in automatically ...
        });
    }

    private void onMouseDown() {
    }
}
like image 188
Logan Pickup Avatar answered Nov 04 '22 13:11

Logan Pickup


You can use Gdx.input.justTouched(), which is true in the first frame where the mouse is clicked. Or, as the other answer states, you can use an InputProcessor (or InputAdapter) and handle the touchDown event:

Gdx.input.setInputProcessor(new InputAdapter() {
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if (button == Buttons.LEFT) {
            // do something
        }
    }
});
like image 31
nEx.Software Avatar answered Nov 04 '22 12:11

nEx.Software


Without InputProcessor you can use easy like this in your render loop:

@Override
public void render(float delta) {
    if(Gdx.input.isButtonJustPressed(Input.Buttons.LEFT)){
        //TODO:
    }
}
like image 3
MarsPeople Avatar answered Nov 04 '22 13:11

MarsPeople