I'm not sure if I understand callback functions completely - they are functions that another function calls? This seems like a powerful tool, especially w/r/t handling input. I've written up this quick and dirty example using callbacks(or at least my understanding of them), but I feel as though I am doing too much.
1st, I would gather input from the OS.
2nd, I would pass that input into some sort of Context to handle input.
3rd, I would use the current active Contexts to shoot off these callback functions, based off of the input.
Something like this,
//Gathers keyboard input
struct InputData {
std::map<SDLKey, bool> held_keys;
std::map<SDLKey, bool> pressed_keys;
std::map<SDLKey, bool> released_keys;
};
//Takes a shared_ptr in the constructor so it always knows what the current InputData is
class Context {
public:
//Constructors/Destructors
...
//Maps a function to a SDLKey
void set_held_key_to_function(SDLKey key, std::function func)
{
held_key_action[key] = func;
}
void set_pressed_key_to_function(SDLKey key, std::function func)
{
pressed_key_action[key] = func;
}
void set_released_key_to_function(SDLKey key, std::function func)
{
released_key_action[key] = func;
}
//Fires off actions of pressed keys
void PressKey(SDLKey key)
{
if(input_->pressed_keys[key] == true) {
pressed_key_action[key]();
}
}
//Fires off actions of held keys
void HeldKey(SDLKey key)
{
if(input_->held_keys[key] == true) {
held_key_action[key]();
}
}
//Fires off actions of released keys
void ReleasedKey(SDLKey key)
{
if(input_->released_keys[key] == true) {
released_key_action[key]();
}
}
private:
std::shared_ptr<InputData> input_;
std::map<SDLKey, std::function> held_key_action;
std::map<SDLKey, std::function> pressed_key_action;
std::map<SDLKey, std::function> released_key_action;
};
Is this a viable way to handle user input, especially considering that the input in a Pause Menu would be vastly different than the input in the actual Gameplay part? Or am I vastly over-complicating the entire process of handling input? Am I even understanding callbacks correctly?