简体   繁体   中英

Box2D move bodies at same rate regardless of FPS

Sorry, I couldn't word my title properly but I will explain my problem with more clarity here.

I am using libgdx.

When I want to move a Texture so that it covers the same distance with all FPS I will do this:

//...define Player class with x property up here.

Player player = new Player();
int SPEED = 100
public void render() {
    player.x += SPEED * Gdx.graphics.getDeltaTime();
}

Now I want to know how to do this to have the same affect on a body in box2d. Here is an example(the render method of a class that extends ApplicationAdapter):

public void render() {

    //clear screen, ... do other stuff up here.

    playerBody.applyForce(new Vector2(0.5f / PIXEL_PER_METER, 0.0f), playerBody.getWorldCenter(), true);
    //PIXEL_PER_METER -> applied to scale everything down

    //update all bodies
    world.step(1/60f, 6, 2);
}

This applies a force on the playerBody so that it's acceleration increases. How do I make shore, just like with my first example, that how fast the body is travelling stays constant across at 30fps, 10fps, 60fps, etc. I know the timeStep parameter of the world.step is the amount of time to simulate but this value shouldn't vary.

Thankyou in advance.

I wouldn't use a variable timestep - this is the approach I've used:

private float time = 0;
private final float timestep = 1 / 60f;

public void updateMethod(float delta) {
    for(time += delta; time >= timestep; time -= timestep)
        world.step(timestep, 6, 2);
}

Basically a variable-ish timestep, but uniformly updating.

If you run your game at very low FPS, or if you force it to with the application configuration (eg for testing) this will keep updating at roughly the same speed as a normal 60 FPS instance.

Take a look at Fix your timestep!

You can update all bodies with delta (not 1/60 fixed delta)

world.step(Gdx.graphics.getDeltaTime(), 6, 2);

EDIT: As @Tenfour04 mentioned, in order to prevent high delta values (causes huge jumps), we mostly set a cap for delta.

world.step(Math.min(Gdx.graphics.getDeltaTime(), 0.15f), 6, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM