我的游戏中的物理在 vsync 关闭时给出了错误的结果 C++

问题描述

我在 2D 游戏中根据引力计算牛顿物理学。当 vsync 打开 (60fps) 时,它完全按照预期工作,但是一旦我关闭它并获得大约 3.5k fps,角色开始以惊人的速度下降。答案似乎很明显,我只需要将角色的速度乘以 deltaTime,但我已经这样做了,但仍然没有结果。它稍微减慢了角色的速度,但似乎还不够..

这是角色的更新函数的样子:

void Update(float deltaTime) {
  if (!onGround) {
    acceleration += -Physics::g; // 9.81f
    /* EDIT: THIS IS WHAT IT ACTUALLY LOOKS LIKE,sorry*/
    SetPosition(position + Vec2(0.0f,1.0f) * deltaTime * acceleration);
    /* instead of this:
    SetPosition(position + Vec2(0.0f,1.0f) * acceleration); */
    if (ceiling) {
      acceleration = 0;
      ceiling = false;
    }
  } else {
    acceleration = 0;
  }
}

这里是 deltaTime 的计算

inline static void BeginFrame() {
  currentTime = static_cast<float>(glfwGetTime()); // Time in seconds
  delta = (currentTime - lastTime);
  lastTime = currentTime;
}

我错过了什么? 提前致谢。

解决方法

加速度是指单位时间内速度增加的幅度,因此您应该将deltaTime乘以加速度,而不仅仅是乘以速度。

换句话说,

acceleration += -Physics::g; // 9.81f

应该是:

acceleration += deltaTime * -Physics::g; // 9.81f