I'm making a 2D platformer on Android using libGDX. One thing I've had a problem with recently is gravity and jumping. I found a few tutorials on the internet and was able to come up with this...
public static final int JUMP_HEIGHT = 64;
public static final float JUMP_GRAVITY= -6.0f;
public static final float MAX_GRAVITY = 20.0f;
public static final float GRAVITY= 19.0f;
private void updateGravity(float delta) {
if(Gdx.input.isTouched() && !jumping) {
jumping = true;
gravity = Config.JUMP_GRAVITY;
}
if(jumping) {
// change frame to jump
sprite.setRegion(walkFrames[0]);
sprite.translate(0, (-1*gravity));
// runner has landed?
if(sprite.getY() <= idleY) {
jumping = false;
sprite.setPosition(Config.RUNNER_X, idleY);
}
// slowdown / fall
if (gravity < Config.MAX_GRAVITY) gravity += Config.GRAVITY*delta;
}
}
The code works and my character will jump and fall smoothly. Although the time it takes for him to jump and comedown is independent from delta the height he jumps is not. If the device lags while jumping he will jump only a portion of how high he should. For the life of me I cannot get it to make sure it jumps a specific height (JUMP_HEIGHT) and in a specific time independent of the delta.