Reputation: 5
I am making a simple game in C# using the XNA 4.0 framework but am having problems implementing a pause feature.
I want it to start off paused then, upon hitting the P key unpause and start gameplay, then at any time when P is pressed, pause it again. So far it starts off paused and toggles to playing but won't pause once it starts playing. Here's my code for the pausing upon pressing P
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
this.Exit();
}
KeyboardState newState = Keyboard.GetState();
// Is P key down?
if (newState.IsKeyDown(Keys.P))
{
// If P key is down now but not down last update and game isn't paused; pause
if (!oldState.IsKeyDown(Keys.P) && !paused)
{
// Pausing the game
paused = true;
pauseScreen = true;
}
// If P key is down now but not last update and game is pause; unpause
if (!oldState.IsKeyDown(Keys.P) && paused)
{
// Unpausing
paused = false;
pauseScreen = false;
}
}
oldState = newState;
paused is a boolean as is pauseScreen both are used to trigger if statements that pause/unpause the game and display/hide the backsplash I'm using. Those are working perfectly fine, it's the bit above that's causing me troubles.
Any ideas why it registers only one press of the P key and not every time it's pressed?
Sorry if this seems stupid, it's late and I can't think of any reason why this wouldn't work.
Upvotes: 0
Views: 424
Reputation:
bool isPause;
bool isPauseKeyDownHandled;
bool isPauseKeyDown = ...;
if (isPauseKeyDown)
{
if (!isPauseKeyDownHandled)
{
isPause = !isPause;
isPauseKeyDownHandled = true;
}
}
else
{
isPauseKeyDownHandled = false;
}
Or using this:
CustomKeyInputManager keyInputManager;
Initialize()
{
keyInputManager = CustomKeyInputManager();
keyInputManager.RegisterKey("pause", Keys.P);
}
Update(GameTime pGameTime)
{
keyInputManager.Update(pGameTime);
if (keyInputManager["pause"].IsPressedAndNotHandled)
{
pause != pause;
keyInputManager["pause"].SetHandled();
}
}
Upvotes: 2