a note from the translation
Wiki Style Guide
Event handling allows you to get more granular and most of all chronological information about input from the user. Event handling provides a way to implement interactions with user interfaces, where specific input sequences are important, e.g. touch down, touch up on a button means the user clicked the button. Such interactions are hard to implement with polling.
Event handling is done using the common observer pattern. First we have to implement a listener interface called InputProcessor:
public class MyInputProcessor implements InputProcessor {
@Override
public boolean keyDown (int keycode) {
return false;
}
@Override
public boolean keyUp (int keycode) {
return false;
}
@Override
public boolean keyTyped (char character) {
return false;
}
@Override
public boolean touchDown (int x, int y, int pointer, int button) {
return false;
}
@Override
public boolean touchUp (int x, int y, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged (int x, int y, int pointer) {
return false;
}
@Override
public boolean touchMoved (int x, int y) {
return false;
}
@Override
public boolean scrolled (int amount) {
return false;
}
}
The first three methods allow you to listen for keyboard events:
The next three methods report mouse/touch events:
Buttons.Left
for touch screens).Gdx.input.isButtonPressed()
to check for a specific button.touchDragged()
events.Each of the methods returns a boolean
. We'll look into why that is in the InputMultiplexer section below.
Once you implement your InputProcessor
you have to tell libgdx about it so it can be called when a new input event arrives:
MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);
From this point on, all new input events will be pushed to the MyInputProcessor
instance. Events are dispatched right before the call to ApplicationListener.render()
, on the rendering thread.
Sometimes you want to chain InputProcessors
, e.g. you have one processor for your UI which should be invoked first, and a second processor for input events that manipulate your game's world. You can use the InputMultiplexer class to achieve this:
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(new MyUiInputProcessor());
multiplexer.addProcessor(new MyGameInputProcessor());
Gdx.input.setInputProcessor(multiplexer);
The InputMultiplexer
will hand any new events to the first InputProcessor
that was added to it. If that processor returns false from the method invoked to handle the event, this indicates the event was not handled and the multiplexer will hand the event to the next processor in the chain. Through this mechanism, the MyUiInputProcessor
can handle any events that fall inside one of its widgets and pass on any other events to the MyGameInputProcessor
.