Sunday, March 21, 2010

Event based KeyboardManager

I've written a keyboard manager class that calls events when a keyboard key is pressed, it uses the C# version of function pointers, called "delegates". It makes input handling much easier and cleaner, and provides events that are more useful than the raw XNA keyboard checking.

Class: http://mage360.pastebin.com/bRX9qd2s

Implementation example: http://mage360.pastebin.com/dAgsCEkn

1 comment:

  1. Nicely done, though I think it can be made even better:

    - Calling GetPressedKeys() creates a new Keys[] array each time it is called, feeding the garbage collector. Maybe you could check the difference yourself?
    - Instead of delegates, you could use events (you're essentially already running the exact same code an event would use, you only didn't declare them as events)
    - Check whether someone is subscribed to the events/delegates before comparing the states. That way, if nobody is interested in hearing about key changes, you don't waste time looking for them (on the other hand, reporting key changes is the sole purpose of your class ;))
    - Make an overload of update() where the KeyboardState is passed to the update() method. That enables people to do input playback, unit testing and avoids calling Keyboard.GetState() twice if the state is required elsewhere, too.

    To avoid the state comparison, you could also hook the game window so Windows notifies you directly when a key is pressed or released (I did this in Nuclex.Input: https://devel.nuclex.org/framework/browser/Nuclex.Input/trunk/Source/Devices/WindowMessageKeyboard.cs) but that's probably overkill for such a neat code snippet :)

    ReplyDelete