16

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.

Zumbarlal Saindane
  • 1,199
  • 11
  • 24
TimSim
  • 3,936
  • 7
  • 46
  • 83

2 Answers2

51

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.

noone
  • 19,520
  • 5
  • 61
  • 76
  • But those InputProcessors are in objects of their own. I wanted each object to handle its own input. If I have to do it in the Screen instance, then there's no need for InputProcessors in each object, I'd have to control them from the Screen object. – TimSim May 08 '14 at 16:00
  • Sorry, I didn't really understand that. – noone May 08 '14 at 16:02
  • I don't understand your example. What's a custom input processor? – TimSim May 08 '14 at 16:10
  • Never mind, I probably don't have a clear understanding on how events propagate. I'll just do it the way I know will work. – TimSim May 08 '14 at 16:19
  • Custom input processor is of course your class that implements the interface `InputProcessor`. – noone May 08 '14 at 16:30
1

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

https://libgdx.info/multiplexing/

I hope it helps

Julien
  • 1,028
  • 9
  • 18