Tag Archives: controls

Simple KeyPress Buffer

Using a keyboard buffer for intuitive user inputs

Objective: Using a keyboard buffer for intuitive user inputs
Difficulty: Beginner
Code length: Short
Until recent years, user inputs had often been neglected in software development. After all, controllers and keyboards are rather idiot proof, there are only so many ways to use them Is it?
In a simple walk around the world program, the user press  ‘a’, the avatar move left. Alright now the user press ‘s’, so the avatar move down. Now the user press both ‘a’ and ‘s’, intuitively the avatar move south west.
What happen if the gameplay do not support diagonal movement?. The avatar move the direction of the last key pressed. However if the player release the ‘s’ key while holding ‘a’ key. This is where keyboard buffering come into play.
In many gameplay situations, it may not be feasible to process certain key inputs simultaneously. This article will explain how to create a simple keyboard buffer for an arcade style game movement.
This is a simple buffer for two keys, which I am going to store as a player actions.
_lastActions[1] is the latest player action.
_lastAction[0]  is the action buffer.
The default action for the buffer is  PLAYER_NOT_MOVING, this is what happens when the player releases both keys
//When key is pressed, save the previous action.
void keyPressed(KeyEvent e)
   if(e.key == keyMap[PLAYER_MOVE_UP])
      _lastActions[0] = _lastActions[1];
      _lastActions[1] = PLAYER_MOVE_UP;
      //player move up
Here will check which key the player release, did he release the latest key?, If so process the buffer.
In any case got to reset the action buffer.
void keyReleased(KeyEvent e)
   if(_lastActions[1] == PLAYER_MOVE_UP)
      _lastActions[1] = _lastKeys[0];
      //process the previous player action.
      _lastActions[0] = PLAYER_NOT_MOVING;
   else if(_lastActions[0] == PLAYER_MOVE_UP)
      _lastActions[0] = PLAYER_NOT_MOVING;
It is not a good idea to map the keyPressed to the keycode as in “if(e.key == key.ESCAPE)”. A better pratice is to store all the keycodes in an array and use an enum of player actions  to reference them. In this way not only your keys configuration can be read from an external file, you can also customise your keys during gameplay.
Here is an example of how to reference your keycodes from an enum.
enum playerInputs
KeyCode[] keyMap = new keyMap[PLAYER_INPUTS_COUNT]; //populate your array.