LibGdx physics is independent of frame rate

I work on simple gaming platforms like Super Mario. I am using Java with the LibGdx engine. I have a problem with physics that is independent of the frame rate. In my game, a character can make a jump, the height of the jump, apparently, depends on the frame rate.

The game works fine on my desktop, it runs at 60 frames per second. I also tried a game on a tablet on which it worked with lower fps. It so happened that the character could jump much higher than when I hopped onto the desktop version.

I have already read several articles about fixing timestep, I understand this, but not enough to apply it to this situation. It just seems to me that something is missing.

Here 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();
}

jump() jump_velocity = 40 .y.

.

+3
1

, :

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

. :

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

, box2D, :)

+5

All Articles