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

Started by
5 comments, last by MARS_999 11 years, 10 months ago
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?
Advertisement
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.
Don't thank me, thank the moon's gravitation pull! Post in My Journal and help me to not procrastinate!
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.
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.
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.
Relevant.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]


Relevant.


Thanks ApochPiQ I will take a look at it.

This topic is closed to new replies.

Advertisement