Efficiently checking input and firing events

Posted by Jim on Game Development See other posts from Game Development or by Jim
Published on 2012-06-06T02:12:23Z Indexed on 2012/06/06 4:48 UTC
Read the original article Hit count: 473

Filed under:
|
|
|
|

I'm writing an InputHandler class in XNA, and there are several different keys considered valid input (all of type Microsoft.XNA.Framework.Input.Keys). For each key, I have three events:

internal event InputEvent XYZPressed;
internal event InputEvent XYZHeld;
internal event InputEvent XYZReleased;

where XYZ is the name of the Keys object representing that key. To fire these events, I have the following for each key:

if (Keyboard.GetState().IsKeyDown(XYZ))
{
  if (PreviousKeyState.IsKeyDown(XYZ))
  {
    if (XYZHeld != null)
      XYZHeld();
  }
  else
  {
    if (XYZPressed != null)
      XYZPressed();
  }
}
else if (PreviousKeyState.IsKeyDown(XYZ))
{
  if (XYZReleased != null)
    XYZReleased();
}

However, this is a lot of repeated code (the above needs to be repeated for each input key). Aside from being a hassle to write, if any keys are added to/removed from the keys (if functionality is added/removed), a new section needs to be added (or an existing one removed).

Is there a cleaner way to do this? Perhaps something along the lines of

foreach key
  check which state it's in
  fire this key's event for that state

where the code does the foreach (automatically checking exactly those keys that "exist") rather than the coder?

© Game Development or respective owner

Related posts about XNA

Related posts about c#