Player yVelocity

Well I have this piece of code that I'm trying to get to work, basically I want to accelerate the yVelocity of the player as long as space bar is held down, now obviously there should be a maximum limit where the player would stop and come down.

I have physics working and everything else, I set a Boolean to true when space is held down and set it to false otherwise then, if it is true then I do this
yVelocity = -yAcceleration; I apply gravity constantly so force is always affecting the "player", thing is I can't get it to work the way I want it, as long as the space bar is held and the yvelocity max hasn't being reached, I want to add the upwards force, but like in real life gravity is being a bitch...

1
2
3
4
if(actingLaws & l_gravity )
    {
        yAccel  = 0.50;
    }

This code just applies gravity constantly.

1
2
3
4
5
yVelocity   += yAccel* delta;

/...
if(yVelocity > yMaxVel) yVelocity = yMaxVel;
    if(yVelocity < -yMaxVel) yVelocity = -yMaxVel;


Any help would be appreciated, thanks.
For my game I approached this differently. Rather than increase velocity as long as the jump button is held, you do a FULL jump as soon as it's pressed no matter what. Then when it's released you kill upward velocity.

Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
// assuming negative y is upwards
// do this every frame:
if( jump_was_just_pressed )
  yVelocity -= jump_speed;  // jump_speed is a constant that determines maximum jump height

else if( jump_was_just_released )
{
  // you can change '0' here to be some other constant
  if( yVelocity < 0 )
    yVelocity = 0;
}

yVelocity += gravity_constant;
Last edited on
Thank you for the quick reply sir, this is exactly what I needed :) but as long as you hold the space bar it will keep jumping, so I just have to add an extra check for that, I can't believe I overlooked this... I guess when you don't get much sleep your brain starts malfunctioning xD, thanks.
button pressed != button down

Only jump when the button transitions from a "released" to a "pressed" state. And only stop the jump when it transitions from a "pressed" to a "released" state.
Yeah but as long as you hold down the key it will never be "released".
Right... so your jump will complete its full course.

Note you only apply the upward velocity once, but you apply downward gravity repeatedly, every frame. So once gravity overpowers the initial burst of upward force, the player will be at the peak of their jump. And at that point it doesn't matter if they keep holding the jump button or not, because either way they'll start to fall.
got it ;)
Topic archived. No new replies allowed.