Search code examples
c#xna

Check if a key is released after pressed C# XNA


I got some code to check if the player pressed a certain key. When the player presses the space bar the sprite goes up. But I'm trying to figure out to set the sprite back to the ground when the key is released. This is the code that I came up with:

keystate = Keyboard.GetState();
if (keystate.IsKeyDown(Keys.Right))
     playerPosition.X += 2.0f;
else if (keystate.IsKeyDown(Keys.Left))
     playerPosition.X -= 2.0f;
else if (keystate.IsKeyDown(Keys.Space))
{
   if (keystate.IsKeyDown(Keys.Space))
       playerPosition.Y -= 6.0f;
   else if (keystate.IsKeyUp(Keys.Space))
        playerPosition.Y += 6.0f;
}

I dont want the sprite to get moved when the spacebar isn't pressed. Any solutions would be greatly appreciated?

EDIT: The sprite does move UP, but never goes down!


Solution

  • You've got a check of IsKeyUp on the Spacebar in a clause that only gets entered if the Spacebar is down!

    Get rid of all the redundant else statements and do an additional check on the Key Up which stops the player moving if it hits the ground, so something like:

    keystate = Keyboard.GetState();
    
    if (keystate.IsKeyDown(Keys.Space) && playerPosition.Y >= MinYPos)
    {
           playerPosition.Y -= 6.0f;
    }
    
    if (keystate.IsKeyUp(Keys.Space) && playerPosition.Y <= MaxYPos)
    {
            playerPosition.Y += 6.0f;
    }