我正在使用Super Mario等简单平台游戏。我正在与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.add(0, world.getGravity());
修改速度时,您还需要扩展重力。尝试:
velocity.add(0, world.getGravity() * deltaTime);
在单独的音符上尝试使用Box2D,可以为您处理这些:)