# How are you dealing with user input key bindings...

This topic is 2177 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am not sure how to go about the user input key bindings.

If player sets MoveFwd to S and then later W I would like to find some way to only call the function that actually moves the player and isn't dependent on the actual keycode.

e.g.
 swtich(keycode) { case sf::Keyboard::S: MoveFwd(); break; } 

there has to be some other way to deal with this maybe send in the keycode to a dispatcher() and do something there?

##### Share on other sites
there are various ways. As with all systems the level of complexity depends on the complexity of the game. With the example you posted, you could upgrade that simply to this:

 switch(keycode) { case KeyBindings::Forward: break; case KeyBindings::Backward: break; }; 

Despite my OOP background I like to put these in a class with static methods to load / save key bindings from file.

##### Share on other sites
One of the simplest ways is to use a an intermediate format and then perform the switch on that. As a brief (and terrible) example:
 // we assume your "game" keybinds are enumerations or static ints // can be whatever std::map<KeyBindings::KeyCode, int> keyMap = ... // populate keyMap[KeyBindings.Forward] = MyGameKeyActions.Backward; keyMap[KeyBindings.A] = MyGameKeyActions.Left; keyMap[KeyBindings.Enter] = MyGameKeyActions.Fire; // ... etc. ... // obtain the user key code from somewhere KeyBindings::KeyCode keyCode = .... // obtain the "true" bind from your map if(keyMap[keyCode] != keyMap.end()) { switch(keyMap[keyCode]) { case MyGameKeyActions.Backward: player.moveBackward(); // etc. } } // otherwise the bind doesn't map to anything 
That way your internal logic never has to change, but the user is free to fiddle with the physical keys. You do have to do a value search each time you want to change something, but that's why it's simple and the user shouldn't be doing it too often to be a problem anyway.

##### Share on other sites
I like to map key codes to callbacks in a hash map. So when you handle a key press, you look up the callback and away you go. The callback could be a function pointer, an implementation of an Action interface, or whatever you need for your system. You could even go as far as mapping actions to multiple input types if you need it.

EDIT: Which is what Kyan just posted above. Edited by Aldacron

##### Share on other sites
Thanks Kyan that is kind of what I am trying to do now... I will give it a go and let you guys know if I run into any issues.

##### Share on other sites

Relevant.

Thanks ApochPiQ I will take a look at it.

• 10
• 19
• 14
• 19
• 15