Search code examples
javakeyboardlwjgl

How to overwrite a key press in LWJGL


i'm using the keyboard class from the LWJGL and am currently using

if(Keyboard.isKeyDown(Keyboard.KEY_A))
{
   //move left
}
else if(Keyboard.isKeyDown(Keyboard.KEY_D))
{
   //move right
}

if i have the 'a' key down then the 'd' key it will move right but if i have the 'd' key down then the 'a' key it will still continue to move right due to the "else" part.

i've tried it without the else and just letting them both run but if both keys are press there is no movement

im looking for a piece of code that allows me to only take the input from the last key that was pressed.

i also need to be able to move up and down (using 'w' and 's') so the solution can't stop other keys from working, only 'a' or 'd'.

thanks. Alex.


Solution

  • Use Keyboard.getEventKeyState to determine the current event, followed by Keyboard.getEventKey to determine which key this is. Then, you need to make sure you disable repeat events via Keyboard.enableRepeatEvents. Maintain state for the current movement, changing based on these events, and every tick move accordingly. Something like the following, as quick sketch:

    Keyboard.enableRepeatEvents(false);
    ...
    /* in your game update routine */
    final int key = Keyboard.getEventKey();
    final boolean pressed = Keyboard.getEventKeyState();
    final Direction dir = Direction.of(key);
    if (pressed) {
      movement = dir;
    } else if (movement != Direction.NONE && movement == dir) {
      movement = Direction.NONE;
    }
    ...
    /* later on, use movement to determine which direction to move */
    

    In the above example, Direction.of returns the appropriate direction for the pressed key,

    enum Direction {
      NONE, LEFT, RIGHT, DOWN, UP;
    
      static Direction of(final int key) {
        switch (key) {
          case Keyboard.KEY_A:
            return Direction.LEFT;
          case Keyboard.KEY_D:
            return Direction.RIGHT;
          case Keyboard.KEY_W:
            return Direction.UP;
          case Keyboard.KEY_S:
            return Direction.DOWN;
          default:
            return Direction.NONE;
        }
      }
    }