我正在试着根据物体的速度来确定要提前多远才能检查到壁架。这样,物体就可以停止加速,并让摩擦力停止它。

the problem
摩擦力是每一步0.9 * horizontalSpeed。
当horizontalSpeed小于0.001时,我们将horizontalSpeed设置为0
达到0.001需要多长时间horizontalSpeed =1
当前如何解决问题
var horizontalSpeed = 1
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = 0
while(horizontalSpeed > closeEnoughToZero) {
horizontalSpeed *= friction
distance += horizontalSpeed
}
console.log(distance) // 8.99
可能的解决方案,我只是觉得它有点蛮力,可能是某种类型的数学函数,对此很方便!
发布于 2018-06-18 08:46:10
这里有一个“纯数学”的解决方案
var horizontalSpeed = 1
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = (horizontalSpeed * friction)/(1-friction)
console.log(distance)
或者,给出一个“足够接近于零”,这也可以在没有循环的情况下完成
var horizontalSpeed = 1
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = 0
// this is the power you need to raise "friction" to, to get closeEnoughToZero
let n = Math.ceil(Math.log(closeEnoughToZero)/Math.log(friction));
// now use the formula for Sum of the first n terms of a geometric series
let totalDistance = horizontalSpeed * friction * (1 - Math.pow(friction, n))/(1-friction);
console.log(totalDistance);
我使用Math.log(closeEnoughToZero)/Math.log(friction)的Math.ceil -在您的例子中是66。如果在代码中添加了循环计数器,则会看到该循环执行了66次
而且,正如您所看到的,第二个代码生成的输出与您的循环完全相同。
https://stackoverflow.com/questions/50901417
复制相似问题