我正在尝试使用“阻尼”属性逐渐降低物体的速度。之后,我想使用速度移动对象的位置。它看起来像这样:
velocity.x *= velocity.damping;
velocity.y *= velocity.damping;
x += velocity.x;
y += velocity.y;
没有比这更简单的了,它工作得很好,但这是我的问题:我使用了一个 deltaTime 变量,它包含我的游戏循环的最后一次更新所花费的时间(以秒为单位)。应用速度很容易:
x += velocity.x * deltaTime;
y += velocity.y * deltaTime;
但是,当我乘以阻尼属性时,如何计算 deltaTime?我的想法是,找到 x 或 y 中的位移并将 deltaTime 乘以该位移,如下所示:
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
velocity.y += (velocity.y * velocity.damping - velocity.y) * deltaTime;
事实证明这是行不通的。我真的不明白为什么,但是当我测试它时,我总是得到不同的结果。如果我只是忽略阻尼或将其设置为 1.0,则一切正常,因此问题必须出在最后两行。
最佳答案
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
这意味着你有一个恒定的加速度,而不是阻尼。
velocity.x * (1 - velocity.damping)
是您在一个时间单位内从当前值减少速度的量。它与当前速度成正比,因此在下一个时间单位中,您将使用阻尼因子将速度减少较小的量。但是乘以
deltaTime
,您减去相同数量,从所有 deltaTime
中的起始值计算得出时间单位。假设阻尼系数为
0.9
,因此您在每个时间单位中将速度减少十分之一。如果您使用线性公式(乘以 deltaTime
),则在 10 个时间单位后,您的速度将变为 0,而在 11 个时间单位后,它会切换方向。如果你逐步前进,从 v_0 = 1
的初始速度开始,你会得到v_1 = v_0*0.9 = 0.9
v_2 = v_1*0.9 = 0.81
v_3 = v_2*0.9 = 0.729
v_4 = v_3*0.9 = 0.6561
等等,速度下降较慢。如果展开
v_4
的公式, 你得到v_4 = v_3*0.9 = v_2*0.9*0.9 = v_1*0.9*0.9*0.9 = v_0*0.9*0.9*0.9*0.9 = v_0 * 0.9^4
所以,概括地说,你会看到公式应该是
velocity.x *= Math.pow(velocity.damping, deltaTime);
(假设 Action Script 与 ECMA Script 在该函数的调用方式上没有区别。)
velocity.y
类似当然。
关于actionscript-3 - 使用 deltaTime 阻尼速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14013248/