@Luca_Carminati wrote:
Hello all.
Imagine you're coding a game in which you have a spaceship and want it shoots only once every time you press the spacebar. If you want to shoot again you have to release and press the spacebar again. For what I know MonoGame doesn't have a practical and easy way to handle the keyboard input for such a situation, so I coded this simple class:using Microsoft.Xna.Framework.Input; public class Keyboard { static KeyboardState currentKeyState; static KeyboardState previousKeyState; public static KeyboardState GetState() { previousKeyState = currentKeyState; currentKeyState = Microsoft.Xna.Framework.Input.Keyboard.GetState(); return currentKeyState; } public static bool IsPressed(Keys key) { return currentKeyState.IsKeyDown(key); } public static bool HasBeenPressed(Keys key) { return currentKeyState.IsKeyDown(key) && !previousKeyState.IsKeyDown(key); } }
The class has a HasBeenPressed method that returns true only the first time a key is pressed.
Usage:using Microsoft.Xna.Framework.Input; ... KeyboardState keyState = Keyboard.GetState(); if (Keyboard.HasBeenPressed(Keys.Space)) { Shoot(); // Shoot only once. To shoot again release/press the spacebar } if (Keyboard.IsPressed(Keys.Right)) { MoveShipToRight(); // Move the ship to right while the right arrow key is pressed }
What do you think about it? Is there a simpler way to do the same?
I think future versions of MonoGame should implement a similar feature...
Posts: 1
Participants: 1