Presumably this code is called once every frame. What is likely happening is that while you hold down the up arrow, you are constantly toggling the state of jumping
, which means you take the positive branch of the if
every even frame and the negative branch every odd frame.
That also means you constantly toggle the velocity between -0.4
and 0.2
. Every frame you presumably process that velocity and offset the player by it; however, because your upwards velocity exceeds your downwards velocity, you'll have a net upwards movement.
For example:
On frame 0 you starting hold up. That sets your velocity to -0.4 (and jumping
to true
) and then you add that velocity to the player's position, giving you a delta in of Y of -0.4.
The next frame you are still holding up, but jumping
is now true, so you take the negative branch, setting velocity to 0.2 and jumping to false
. When you apply velocity to position, you have a net delta of -0.4 + 0.2 = -0.2
.
Now, the third frame you are still holding up but jumping
is now false, so you take the positive branch, set velocity to -0.4 and jumping to true. When you apply velocity to position you have a net delta of -0.2 - 0.4 = -0.6
.
That's why your player always moves up.
To fix this, you could restructure the condition as follows:
if (inp.isKeyDown(Input.KEY_UP)) {
if (!jumping) {
jumping = true;
velY=-0.4f;
}
} else {
jumping = false;
velY=0.2f;
}
This means that if the up key is held, you start jumping if you have not already. If the up key is not held, you cancel the jump.