Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libgdx multiple objects implementing InputProcessor

Tags:

java

libgdx

So on my Screen I have two objects of the same class that implement InputProcessor with the following keyDown() method:

@Override
public boolean keyDown(int keycode) {
    if (keycode==fireKey) {
        System.out.println("Reporting keydown "+keyCode);
    }
    return false;
}

The problem is when I instantiate these two objects, only the last one instantiated receives any keyDown events. I need both objects (or however many there are) to receive keyDown events.

like image 851
TimSim Avatar asked May 08 '14 15:05

TimSim


2 Answers

You need to use an InputMultiplexer to forward the events to both InputProcessors. It will look like this:

InputProcessor inputProcessorOne = new CustomInputProcessorOne();
InputProcessor inputProcessorTwo = new CustomInputProcessorTwo();
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(inputProcessorOne);
inputMultiplexer.addProcessor(inputProcessorTwo);
Gdx.input.setInputProcessor(inputMultiplexer);

The multiplexer works like some kind of switch/hub. It receives the events from LibGDX and then deletegates them to both processors. In case the first processor returns true in his implementation, it means that the event was completely handled and it won't be forwarded to the second processor anymore. So in case you always want both processors to receive the events, you need to return false.

like image 69
noone Avatar answered Oct 18 '22 17:10

noone


Here is a code sample on LibGDX.info showing how to implement multiplexing with LibGDX:

https://libgdx.info/multiplexing/

I hope it helps

like image 42
Julien Avatar answered Oct 18 '22 18:10

Julien