Keybindings

A simple way to handle keybindings for games is what I call actionmap. An actionmap is a one-way mapping between a key and an action. Actionmaps allows easy configurable keybindings, changable during runtime. It is also worth reading the article about keycodes versus ascii. Similar techniques is used by many game engines.

Actions
An action is something that should happen, moving forward for instance. Actions may be defined by a simple enum, as in listing 1. Another way might be to use strings as we could easily invent new actions from the game logic. Performance should not be a great deal since actions isn't checked that often, not even when smashing the keys. Actually, the way you represent an action doesn't matter at all.

 enum Action { NO_ACTION,

MOVE_FORWARD, MOVE_BACKWARD, STRAFE_LEFT, STRAFE_RIGHT, PRIMARY_FIRE, SECONDARY_FIRE,

ACTION_MAX };

The Actionmap
A very simple actionmap would be a c-style array where each possible key represents an action. If the key should not represent an actual action it defaults to NO_ACTION. When a key is pressed you simply use the key as the index in the array to get the related action. This is not always the best solution but it works in quite well most of the time. A better way is to implement it using an stl::map. Thus we won't have to store actions for all possible keys. But how about mouse input? I've have been very successful just offsetting the mouse button by the last key. So the first mousebutton would equal KEY_MAX + 0 and the second KEY_MAX + 1 etc.



// Simple actionmap where each possible key represents an action (default: NO_ACTION). Action actionmap[KEY_MAX];

// Reset all actions to NO_ACTION for ( int i = 0; i < KEY_MAX; i++ ){ actionmap[i] = NO_ACTION; }

// Setup some keybindings actionmap[KEY_W] = MOVE_FORWARD; actionmap[KEY_S] = MOVE_BACKWARD; actionmap[KEY_A] = STRAFE_LEFT; actionmap[KEY_D] = STRAFE_RIGHT;

Sample implementation
I've written a sample implementation demonstrating the technique described above. The sample is released under GNU Lesser General Public. Feel free to use in your applications.