In my C#/XNA project, I have a “static” class that manages the input. It looks like this:
internal sealed class InputManager
{
public delegate void KeyboardHandler(Actions action);
public static event KeyboardHandler KeyPressed;
private static readonly Dictionary<Actions, Keys> KeyBindings = Main.ContentManager.Load<Dictionary<Actions, Keys>>("KeyBindings");
private static KeyboardState currentKeyboardState;
private InputManager()
{
}
public static void GetInput()
{
currentKeyboardState = Keyboard.GetState();
foreach (KeyValuePair<Actions, Keys> actionKeyPair in KeyBindings)
{
if (currentKeyboardState.IsKeyDown(actionKeyPair.Value))
{
OnKeyPressed(actionKeyPair.Key);
}
}
}
private static void OnKeyPressed(Actions action)
{
if (KeyPressed != null)
{
KeyPressed(action);
}
}
}
So throughout the game, I get the input and check if any key contained in my dictionary is currently pressed (I use a dictionary for key binding purpose – an action is bound to a key). If so, the KeyPressed event is fired with the associated action as argument. By doing this I can subscribe an external class (such as a camera) to this event and do the appropriate thing based on the action (key).
The problem is that I have to test the action in every subscriber’s method like this:
if (action == Actions.MoveLeft)
{
DoSomething();
}
Hence, no matter which key is pressed (as long as it’s part of the dictionary) every subscriber’s method will be called even if it actually doesn’t need to.
I know I could set an event for each action : event MoveLeft, event MoveRight, etc… However, is there a better way to do this like a list of event?
you can use interface to deal with:
for instance:
in your code implement this interface on your subscriber
and after you handle like this: