Customizeable Keyboard Controls for Games

After gaining more experience, this code seems overcomplicated and slow. It does have the feature of being able to map multiple actions to the same buttons, but I struggle to think of a situation where that would be useful. If you want an actually easy way to have simple keyboard input, you can just use an array of booleans to store your key presses:

// 256 length to have 1 index for every value in a char
boolean[] keys = new boolean [256];

void setup() {
  // Do your thing
}

void draw() {
  // Continue doing your thing
}

/*
 * Helper method that returns on true if a key is pressed.
 * Important note that letters only work with CAPITAL letters.
 * The method also works for other buttons like the arrow keys and shift (the key constants).
 */
boolean keyDown(char input) {
  int index = (int) input;
  if(index < 0 || index > 255) return false;
  return keys[index];
}

void keyPressed() {
  if(keyCode < 256) keys[keyCode] = true;
}

void keyReleased() {
  if(keyCode < 256) keys[keyCode] = false;
}

It’s quick to implement, easy to understand, and works for game keyboard controls.
Know its limitations, though. It can’t distinguish capital or lowercase letters and not every key on the keyboard can be detected (see keyCode for more info).
As with most processing games, you’re left to make everything custom. While this code is convenient, I encourage you to test it to understand it, experiment with adding new features, and combine it with other input methods (if necessary) to make your game the best it can be.

1 Like