Keybindings

From Sidvind
Jump to: navigation, search

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[edit]

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.

Code: Listing 1

  1. enum Action {
  2.   NO_ACTION,
  3.  
  4.   MOVE_FORWARD,
  5.   MOVE_BACKWARD,
  6.   STRAFE_LEFT,
  7.   STRAFE_RIGHT,
  8.   PRIMARY_FIRE,
  9.   SECONDARY_FIRE,
  10.  
  11.   ACTION_MAX
  12. };

The Actionmap[edit]

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.

Code: Simple actionmap

  1. // Simple actionmap where each possible key represents an action (default: NO_ACTION).
  2. Action actionmap[KEY_MAX];
  3.  
  4. // Reset all actions to NO_ACTION
  5. for ( int i = 0; i < KEY_MAX; i++ ){
  6.   actionmap[i] = NO_ACTION;
  7. }
  8.  
  9. // Setup some keybindings
  10. actionmap[KEY_W] = MOVE_FORWARD;
  11. actionmap[KEY_S] = MOVE_BACKWARD;
  12. actionmap[KEY_A] = STRAFE_LEFT;
  13. actionmap[KEY_D] = STRAFE_RIGHT;

Sample implementation[edit]

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.