Monogame - Keyboard Input On-Release

Monogame doesn’t provide an onRelease type function for the keyboard input. What this means is that pressing a key to receive one, single input can be a pain.

For example, in my dungeon crawler game, if opening a door I don’t want to have it activate more than once as the activate toggles. So if the door is closed, it will open and vice versa. If you don’t limit the activation to a single instance (like once a key has been released) it becomes luck as to whether the door stays open on activation.

Monogame provides states for its various inputs. By storing the old state of the keyboard you can check if the key was pressed and now released.

1.At the top of the function you take input, store the new state to a local KeyboardState variable

.
  1. Create a class member to store the old state and at the end of the function, store the current new state to the old state.
.
  1. Then where you check which key is pressed (between the new and old state), compare the new state to the old state
.

And there you have an onReleaseKey type function. It checks if the key was pressed last run and if the key is now up. This stops you having multiple, unintended actions happening.