Reputation: 3874
I have researched how to implement a rudimentary gravity system in slick2d. Here is the code that I have (This is in the update function):
if (input.isKeyDown(Input.KEY_UP)) {
spressed = true; //Has the UP key been pressed?
}
if (spressed) {
if (!sjumping) {//if so, are we already in the air?
Sub_vertical_speed = -1.0f * delta;//negative value indicates an upward movement
sjumping = true;//yes, we are in the air
}
if (sjumping) { //if we're in the air, make gravity happen
Sub_vertical_speed += 0.04f * delta;//change this value to alter gravity strength
}
Sub.y += Sub_vertical_speed;
}
if (Sub.y == Sub.bottom){//Sub.bottom is the floor of the game
sjumping = false;//we're not jumping anymore
spressed = false;//up key reset
}
Here is where the problem arises. When I press the up key, the sprite jumps and comes down normally, but pressing the up key again does nothing. I originally thought it was cause I didn't reset spressed, so I added the line to set it to false, but you can still only jump once. :/
Upvotes: 0
Views: 107
Reputation: 335
I've done something similar before, and my assumption here is that Sub.y never equals Sub.bottom. Depending on the y position and the vertical speed, the object's y position will never be exactly the value of Sub.bottom. The code below will test for this:
if (Sub_vertical_speed + Sub.y > Sub.bottom){ //new position would be past the bottom
Sub.y = Sub.bottom;
sjumping = false; //we're not jumping anymore
spressed = false; //up key reset
}
Upvotes: 0
Reputation: 1051
It looks like your Sub.y needs to be Clamped to your Sub.bottom so it doesn't go above it. Try:
if(Sub.y >= Sub.bottom) {
Sub.y = Sub.bottom;
sjumping = false;
spressed = false;
}
Upvotes: 1