Java – Framerate-independent LibGdx physics

Framerate-independent LibGdx physics… here is a solution to the problem.

Framerate-independent LibGdx physics

I’m working on a simple platformer like Super Mario. I use Java with the LibGdx engine. My physics issue has nothing to do with frame rate. In my game, characters can jump, and the jump height obviously depends on the frame rate.

On my desktop, the game runs fine, running 60 frames per second. I’m also running the game at lower fps on my tablet. What happens is that the characters can jump much higher than I did on the desktop version.

I’ve seen a few articles about fixed time steps and I do understand it, but not enough to apply it to this situation. I seem to be missing something.

This is the physical part of the code:

protected void applyPhysics(Rectangle rect) {
    float deltaTime = Gdx.graphics.getDeltaTime();
    if (deltaTime == 0) return;
    stateTime += deltaTime;

velocity.add(0, world.getGravity());

if (Math.abs(velocity.x) < 1) {
        velocity.x = 0;
        if (grounded && controlsEnabled) {
            state = State.Standing;
        }
    }

velocity.scl(deltaTime); 1 multiply by delta time so we know how far we go in this frame

if(collisionX(rect)) collisionXAction();
    rect.x = this.getX();
    collisionY(rect);

this.setPosition(this.getX() + velocity.x, this.getY() +velocity.y); 2
    velocity.scl(1 / deltaTime); 3 unscale the velocity by the inverse delta time and set the latest position

velocity.x *= damping;

dieByFalling();
}

Call the jump() function and add the variable jump_velocity = 40 to velocity.y.

Speed is used for collision detection.

Solution

I think your problem lies here :

velocity.add(0, world.getGravity());

You’ll also need to scale gravity when modifying the speed. Try:

velocity.add(0, world.getGravity() * deltaTime);

To illustrate separately, try box2D and it can handle these issues for you 🙂

Related Problems and Solutions