Search code examples
c#.netmonogame

Monogame - Key 'Pressed' instead of 'Hold' to Jump


Will keep this short and simple:

I have a 2D game with a movable character, and I have written some code to allow my player to jump, like so:

if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false)
{
    sound.Play(volume, pitch, pan); // plays jumping sound
    position.Y -= 5f;               // position of jump
    velocity.Y = -10.5f;            // velocity of jump 
    hasJumped = true;
}

However when I hold down the Space Bar , my player will continue to jump when he lands back to the ground, however I want my player to only jump once during the duration of holding down the Space Bar , then having to press it again to jump.

I appreciate any help given.

UPDATE

My velocity resets in one of my collision if statements within my Collision() function:

if (rectangle.touchTopOf(newRectangle))
{
    rectangle.Y = newRectangle.Y - rectangle.Height;
    velocity.Y = 0f;    // velocity reset
    hasJumped = false;
}

Solution

  • As Brian already mentioned you need a variable to remember if the space bar was pressed last tick. Something like this should fix your problem.

    if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false && !spacebarDown)
    {
        sound.Play(volume, pitch, pan); // plays jumping sound
        position.Y -= 5f;               // position of jump
        velocity.Y = -10.5f;            // velocity of jump 
        hasJumped = true;
        spacebarDown = true;
    }
    if(Keyboard.GetState().IsKeyUp(Keys.Space))
    {
        spacebarDown = false;
    }