|
Links of Interest
MainDownload Prerequisites Screenshots Articles/Code Snippets DBP Warmup Entries Blog Contact/Feedback Quick Downloads:
Diaspora
XNA Requirements Installer
External Links
Heather [layout designer]XNA |
Keyboard Component
This component processes keyboard input. It is not currently a GameComponent, but it can easily be adapted to be one. call KeyboardHelper.Update() in the main game loops before everything else. Also, thanks to Shawn Hargreaves, I have removed a bug where the Keys would get boxed each time they were accessed or added to the dictionary, which resulted in several thousand new objects every second. NOTE: I haven't manually added in all the keys yet. If you wish to use a specific key, add it in the component's Update() method.
Here's how to register the events to use the component:
KeyboardHelper.OnKeyDown += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyDown);
And here is the actual component:
KeyboardHelper.OnKeyPressed += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyPressed); KeyboardHelper.OnKeyUp += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyUp); class KeyboardHelper
{ public delegate void KeyEventHandler(Keys key); public static event KeyEventHandler OnKeyPressed; public static event KeyEventHandler OnKeyDown; public static event KeyEventHandler OnKeyUp; static Dictionary<int, bool> keyStates = new Dictionary<int, bool>(); public static void Update() { KeyHelper(Keys.Up); KeyHelper(Keys.Down); KeyHelper(Keys.Left); KeyHelper(Keys.Right); KeyHelper(Keys.Escape); KeyHelper(Keys.Enter); KeyHelper(Keys.LeftControl); KeyHelper(Keys.Space); KeyHelper(Keys.W); KeyHelper(Keys.A); KeyHelper(Keys.S); KeyHelper(Keys.D); KeyHelper(Keys.Q); KeyHelper(Keys.P); } static void KeyHelper(Keys key) { if (!keyStates.ContainsKey((int)key)) keyStates.Add((int)key, false); if (Keyboard.GetState()[key] == KeyState.Down) { if (!keyStates[(int)key]) if(OnKeyDown!=null) OnKeyDown(key); keyStates[(int)key] = true; } else { if (keyStates[(int)key]) if (OnKeyPressed != null) OnKeyPressed(key); if (OnKeyUp != null) OnKeyUp(key); keyStates[(int)key] = false; } } } |