use*_*315 5 math actionscript-3 game-physics
我正在尝试使用"阻尼"属性逐渐降低对象的速度.之后,我想使用速度移动对象的位置.它看起来像这样:
velocity.x *= velocity.damping;
velocity.y *= velocity.damping;
x += velocity.x;
y += velocity.y;
Run Code Online (Sandbox Code Playgroud)
可能没有那么简单,它工作正常,但这是我的问题:我正在使用deltaTime变量,它包含我的游戏循环的最后一次更新所花费的时间(以秒为单位).应用速度很容易:
x += velocity.x * deltaTime;
y += velocity.y * deltaTime;
Run Code Online (Sandbox Code Playgroud)
但是,当我乘以阻尼属性时,如何计算deltaTime?我的想法是,找到x或y中的位移并将deltaTime乘以,如下所示:
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
velocity.y += (velocity.y * velocity.damping - velocity.y) * deltaTime;
Run Code Online (Sandbox Code Playgroud)
原来这不起作用.我真的不明白为什么,但是当我测试它时,我会得到不同的结果.如果我只是忽略阻尼或将其设置为1.0,一切正常,所以问题必须在最后两行.
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
Run Code Online (Sandbox Code Playgroud)
这意味着你有一个恒定的加速度,而不是阻尼.
velocity.x * (1 - velocity.damping)
Run Code Online (Sandbox Code Playgroud)
是在一个时间单位中从当前值递减速度的量.它与当前速度成正比,因此在下一个时间单位中,您可以使用阻尼系数将速度减小一个较小的量.但乘以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
Run Code Online (Sandbox Code Playgroud)
等,速度减慢.如果你展开公式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
Run Code Online (Sandbox Code Playgroud)
所以,推广,你看到公式应该是
velocity.x *= Math.pow(velocity.damping, deltaTime);
Run Code Online (Sandbox Code Playgroud)
(假设动作脚本与调用该函数的ECMA脚本没有区别.)
同样,对于velocity.y课程.