Search code examples
javaandroidlibgdx

libGDX - Using different InputProcessors for different screens?


I don't understand how InputProcessor is supposed to work.

I have multiple Screens for a game. I created a MyInputProcessor class that implements InputProcessor. In my MenuState class I Gdx.input.setInputProcessor to an instance of the class.

  1. First of all, how should I access and set variables that are defined in my MainMenu class in MyInputProcessor? If I want the touchDown method to change a variable for example.

  2. If I switch Screens, do I have to create a new InputProcessor class to check for other touch events? I obviously don't want it to continue checking for things meant for MainMenu class. How am I supposed to use it?

  3. Am I just supposed to create a whole new InputProcessor for each Screen?

I find this all very confusing. Thankful for any help at all.


Solution

  • Yes, usually you create one InputProcessor for every Screen, or even better for every object, that needs to process inputs. This object can be a Screen, but it can be a Player to.
    So every object that needs to get notified about any input should implement InputProcessor and handle the relevant inputs.
    Also make sure to set your InputProcessor as the current, active one (using Gdx.input.setInputProcessor).
    The Screens for example could set themself as the current InputProcessor in the show method (and eventually unregister themself in the hide). IF you want to use multiple InputProcessors at once (for example in the GameScreen, where the Player is controlled using "w,a,s,d", but you want to show a PauseMenu on "Esc"), just use InputMultiplexer and register every InputProcessor on that multiplexer.
    If you use InputMultiplexer, make sure to take care about the return value of your InputProcessor-methods:
    - Return true, if the proccessor handled the event (for example in the Players InputProcessor, when "w", "a", "s" or "d" is pressed). - Return false, when you did not handle the event (for example in the Players InputProcessor, when "Esc" is pressed).
    The InputMulitplexer will go through all it's InputProcessors and send them the event, unitl one of them returns true. All others won't get notified about the event.
    Also note, that Stage is an InputProcessor, which distributes the event to it's Actors. So if you want to handle inputs in your Actors, make sure to set Stage as you current InputProcessor.