Table of contents

  1. Keyboard Detection
    1. Keyboard Input
    2. Key Detection Methods
    3. Supported Keys
    4. Adding More Supported Keys

Keyboard Detection

Keyboard Input

There is a Keyboard class in the engine that handles detecting if a key is currently pressed (or not pressed) on the keyboard at any point while the game is running. The class is a “static” class (meaning it can’t be instantiated and all methods are static) and exists solely to poll the global keyboard state, which is generally used in update methods to check if a certain key is currently being pressed or not. Every class has the ability to detect keyboard input, and multiple classes can detect keyboard input during the same update cycle and react to it as desired.

Key Detection Methods

The Keyboard class supplies the following methods:

  • isKeyDown – check if a key is currently being pressed
  • isKeyUp – check if a key is not currently being pressed
  • areKeysDown – check if multiple keys are being pressed at the same time
  • areKeysUp – check if multiple keys are not being pressed at the same time

Since these methods are all static methods, they can be referenced directly from the Keyboard type.

Using these methods are really easy. There is a Key enum in the engine that has predefined keys set up to be checked for. These can be used as arguments for the Keyboard class’s methods.

public void update() {
    // check if LEFT arrow key pressed
    if (Keyboard.isKeyDown(Key.LEFT)) {
        
    }

    // check if A key is pressed
    if (Keyboard.isKeyDown(Key.A)) {
        
    }
    
    // if 1 key is not pressed
    if (Keyboard.isKeyUp(Key.ONE)) {

    }

    // if both shift and space are pressed at the same time
    if (Keyboard.areKeysDown(new Key[] { Key.SHIFT, Key.SPACE })) {

    }      
}

Supported Keys

List of supported keys
  • UP
  • DOWN
  • RIGHT
  • LEFT
  • ENTER
  • SHIFT
  • A
  • B
  • C
  • D
  • E
  • F
  • G
  • H
  • I
  • J
  • K
  • L
  • M
  • N
  • O
  • P
  • Q
  • R
  • S
  • T
  • U
  • V
  • W
  • X
  • Y
  • Z
  • ONE
  • TWO
  • THREE
  • FOUR
  • FIVE
  • SIX
  • SEVEN
  • EIGHT
  • NINE
  • ZERO
  • SPACE
  • ESC

Adding More Supported Keys

If additional supported keys than the ones included are desired, an entry for it must be added to the Key enum (Key.java), and then an entry also needs to be added to the Keyboard class’s buildKeyMap EnumMap method mapping the enum entry with its key code. You can look up each key’s key code in the StackOverflow answer here. Note: key codes for Java differ slightly from those in JavaScript, which most other websites will give you when googling for key codes – please use the provided link for correct key codes for Java.