我正在开发一个类似于超级马里奥的简单平台游戏,使用Java和LibGdx引擎。我的问题是物理引擎与帧率无关。在我的游戏中,角色可以跳跃,跳跃高度明显与帧率相关。
在我的桌面上,游戏运行良好,每秒运行60帧。我还在平板电脑上尝试了游戏,它以较低的fps运行。结果是,在平板电脑上跳跃的角色比在桌面版本上跳得更高。
我已经阅读了一些有关修复时间步长的文章,我确实理解了其中的内容,但不足以应用到这种情况。我似乎缺少一些东西。
以下是代码中的物理部分:
在我的桌面上,游戏运行良好,每秒运行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 中。
velocity 在碰撞检测中被使用。