LibGdx物理独立于帧速率

时间:2014-02-06 17:15:44

标签: java android libgdx game-physics frame-rate

我正在开发像超级马里奥这样的简单平台游戏。我正在使用带有LibGdx引擎的Java。我有一个物理问题,独立于帧率。在我的游戏中角色可以跳跃,跳跃高度显然取决于帧速率。

在我的桌面上游戏运行正常,它以每秒60帧的速度运行。我也尝试在平板电脑上以较低的fps运行游戏。发生了什么事情,这个角色可能比我跳到桌面版本时跳得更高。

我已经阅读了一些关于修复时间步的文章,我理解它,但还不足以应用于这种情况。我似乎错过了什么。

以下是代码的物理部分:

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添加到velocity.y。

速度用于碰撞检测。

1 个答案:

答案 0 :(得分:5)

我认为你的问题在这里:

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

修改速度时还需要缩放重力。尝试:

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

单独注意,尝试使用box2D,它可以为你处理这些:)