I have a class that manages keyboard input and fires off KeyPressed, KeyReleased, or KeyHeld events. It only fires off an event if the key exists in the KeyBindings collection of my Controller component. Now that I’ve got all of that working I’m stuck on a problem. What I want is the following:
Key pressed.
if(Key bind exists)
Fire key pressed event.
foreach(function in keyBinds)
{
execute function, fire event, whatever...
}
I just can’t figure out how the foreach loop would work. Any ideas on how I could pull something like this off?
KeyboardController Component:
public class KeyboardController : IComponent
{
//Fields
private Dictionary<Keys, HashSet<Delegate>> m_keyBindings = new Dictionary<Keys,HashSet<Delegate>>();
//Properties
public Dictionary<Keys, HashSet<Delegate>> KeyBindings
{
get { return m_keyBindings; }
}
}
This is the class that will contain the Keys and their function/delegate/event/whatever bindings. The code for events CANNOT be contained within this class because the class is meant only to store data. I need to pass a Key bind and an action or set of actions to perform when this bind is pressed.
Adding a bind:
//Set key bindings
KeyboardController kbController = entityManager.GetComponent<KeyboardController>(1);
kbController.KeyBindings.Add(Keys.Up, new HashSet<Delegate>());
kbController.KeyBindings[Keys.Up].Add(function);
I don’t know how to make the third line in “Adding a bind:” work.
You can use a multicast delegate to automatically fire off multiple events for a given key, this way you don’t need to maintain a collection of events. For example:
Hooking events:
If for some reason you didn’t want to use multicast delegates, you could do something like this:
Rather than HashSet use an actual delegate type such as Action<>. For instance: