0

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;
}
toadflax
  • 375
  • 4
  • 17

1 Answers1

2

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;
}
Mormund
  • 328
  • 3
  • 8
  • When declaring spacebarDown, what `bool` value do you set it to? This seems to only work whilst my player is in the air. – toadflax May 02 '16 at 17:53
  • I'd say set it to false but that shouldn't influence anything once you've pressed space once. – Mormund May 02 '16 at 20:31