Box2D 以相同的速率移动物体而不管 FPS

Box2D move bodies at same rate regardless of FPS

抱歉,我无法正确表达我的标题,但我会在这里更清楚地解释我的问题。

我正在使用 libgdx。

当我想移动纹理使其覆盖所有 FPS 相同的距离时,我会这样做:

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

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

现在我想知道如何对 box2d 中的 body 产生同样的影响。这是一个示例(扩展 ApplicationAdapter 的 class 的渲染方法):

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

这会在 playerBody 上施加一个力,使其加速度增加。我如何做岸,就像我的第一个例子一样,body 的行进速度保持恒定在 30fps、10fps、60fps 等。我知道 world.step 的 timeStep 参数是模拟的时间量,但这个值不应该改变。

提前谢谢你。

您可以使用增量更新所有主体(不是 1/60 固定增量)

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

编辑: 正如@Tenfour04 提到的,为了防止高 delta 值(导致巨大的跳跃),我们主要为 delta 设置一个上限。

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

我不会使用可变时间步 - 这是我使用的方法:

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

基本上是一个可变的时间步长,但统一更新。

如果您 运行 您的游戏的 FPS 非常低,或者如果您使用应用程序配置(例如为了测试)强制它,这将继续以与正常 60 FPS 实例大致相同的速度更新。

看看Fix your timestep!