• Advertisement
Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement