我的游戏中的物理在 vsync 关闭的情况下给出了错误的结果 C++
Physics in my game gives a wrong result with vsync turned off C++
我在 2D 游戏中根据引力计算牛顿物理学。当打开垂直同步 (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
我在 2D 游戏中根据引力计算牛顿物理学。当打开垂直同步 (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