As others have mentioned: Immediately after you set the gamestate to paused, it enters the following if-block and sets the state back to playing.
Sure, the simple fix is to include an else
between the two states, but that will cause yet an other problem because the IsKeyDown
will return true
in sequential updates, and since updates happen 40+ times per second, you will temporarily unpause for one frame, then pause the very next, and back and forth until the key is released.
The real solution is to detect the moment when the key is released (or pressed if you want to do it backwards). This can be done by storing the previous keyboard state, and comparing that to the current keyboard state. Something like:
if (LastKeyboardState.IsKeyDown(Keys.P) && !CurrentKeyboardState.IsKeyDown(Keys.P))
{
// The 'P' key has just been released
// This will only fire ONCE when the 'P' key is released
}
I would recommend making a wrapper class for the keyboard that handles this for you, but that is up to you.