Simple key listener

What is the best way to implement a key listener for my game, at the moment I have controls for my character implemented through InputHandler. But I want a few keys to do certain things (ie change variables).



Firstly I want a key to toggle first/third person view in my chaser camera class (one I wrote). I have the logic built up in an update method (if else statements) but I have no implementation to change the variable if a key is pressed and I don't know the best way to implement it. I have looked through the example code but I struggle to discern what is going on in them  XD could someone give me an example on how to do what I want please?



Thanks



Neilos

Thanks, the first example worked wonders. I have been using KeyBindingManager with InputHandler's addAction method, I thought they had to be used in conjunction and didn't realise I could use it in the way you have shown, that actually makes things really easy for me!  XD I'm a happy man lolz, just another 999,999 problems to solve and we'll be there!



Thanks again



Neilos

I was actually working on key bindings myself today! :slight_smile:



As I'm not quite sure what you want to do, here are some alternatives:


KeyBindingManager.getKeyBindingManager().add("a command", KeyInput.KEY_A);
boolean keyPressed = KeyBindingManager.getKeyBindingManager().isValidCommand("a command");


This connects a String command with a key (the A key in this example). You can add several keys to the same command or require a command to only be triggered if several keys are pressed at the same time.
You can then check if the key/keys is/are pressed by using isValidCommand(String command).

InputHandler input = new InputHandler();
input.addAction(new InputAction()  {
           public void performAction(InputActionEvent event) {
              doSomething();
                        myBoolean = true;
           }
        }, "a command", KeyInput.KEY_A, false);


This associates an object implementing InputActionInterface (like InputAction) with a String command and adds a key (in this case the A key) to the KeyBindingManager. The last argument determines if you want this command to be allowed to repeated or not when you hold the key down.
In the performAction method you can do whatever you need to do, like calling a method or setting a variable (if you can access them, of course). It might be a good idea to make your own class implementing InputActionInterface or extending InputAction. Then you can pass fields to it.

boolean keyPressed = KeyInput.get().isKeyDown(key);


Last the simplest method (that is used internally by KeyBindingManager btw.).
This just tells you if the key is pressed at the moment.

Use the one you think fits your requirements best.