Spice up your PC input with extension methods
I started working on a quick game for the latest XNA 7 Day challenge and wanted to simplify my input a bit. I knew I wanted to centralize it all to make things easier, but I also wanted to make the code simpler when I needed to check input. I’m only doing keyboard input, so that helped even more. After a bit of tinkering I came up with a clean solution thanks to extension methods.
First of all, I created a static class to house my current and previous frame’s KeyboardStates as well as my extension methods. The core of the class is really minimal:
public static class KeyboardInputExtensions
{
private static KeyboardState oldKeyState, newKeyState;
static KeyboardInputExtensions()
{
oldKeyState = newKeyState = Keyboard.GetState();
}
public static void Update()
{
oldKeyState = newKeyState;
newKeyState = Keyboard.GetState();
}
}
Then I just add a call to the KeyboardInputExtensions.Update() method in my game’s Update method and I’m ready to go. Next up: the extension methods. I came up with a fun way to make checking for input look like this:
if (Keys.Space.WasJustPressed())
{
player.Jump();
}
else if (Keys.X.IsDown())
{
player.Shoot();
}
I think that looks really clean and makes input checking much quicker than other methods. Supporting this is really easy thanks to a few extension methods I added to my KeyboardInputExtensions class:
public static bool IsDown(this Keys key)
{
return newKeyState.IsKeyDown(key);
}
public static bool IsUp(this Keys key)
{
return newKeyState.IsKeyUp(key);
}
public static bool WasJustPressed(this Keys key)
{
return newKeyState.IsKeyDown(key) && oldKeyState.IsKeyUp(key);
}
public static bool WasJustReleased(this Keys key)
{
return newKeyState.IsKeyUp(key) && oldKeyState.IsKeyDown(key);
}
Pretty nifty, huh? Anyone else have any fun tricks for simplifying code using extension methods or any other technique?
Possibly Related Posts
(Automatically Generated)Extension Methods and You
Finding Distances The Extension Way
.NET Misconceptions Part 1
How Not To Write A Game – Everything Changes
Further extending C# arrays

I’ve got essentially the same thing, but with mouse support.
http://pastebin.com/f1b580141
I’ve got essentially the same thing, but with mouse support.
http://pastebin.com/f1b580141
I use BinaryReader and BinaryWriter frequently, and I like to create specific Read/Write methods for certain types that I use frequently.
http://pastebin.com/f464f276a
I also find it convenient to convert between Points and Vector2s quite frequently.
http://pastebin.com/f4230eefd
Simple, yet convenient.
I use BinaryReader and BinaryWriter frequently, and I like to create specific Read/Write methods for certain types that I use frequently.
http://pastebin.com/f464f276a
I also find it convenient to convert between Points and Vector2s quite frequently.
http://pastebin.com/f4230eefd
Simple, yet convenient.