如何在 X 毫秒内以指数方式平滑地将数字增加到 Y

How to smoothly increase a number to Y in X milliseconds exponentially

我正在 node.js 中制作一个半现实的 'physics' 引擎,如果你甚至可以这样称呼它的话,我想以指数方式加速。例如。 2秒内从0m/s到4.5m/s,然后可能在3秒内减速到0m/s。显然,对于减速部分,我可能可以输入一个负数。

这是我正在考虑的图片,不确定图中我所期望的是否与指数相同。

我没有任何代码,我想我可以将它作为 setInterval 之类的东西的基础,但那将是线性的。

你说得对SetInterval只能提供固定速度,而你需要的是动态速度。

一种方法是制作两个包含相同数量项目的数组。第一个数组名为 duration,第二个名为 speed。变量 Y 将在对应于速度 # 的持续时间内随速度变化。看这里:

var Y = 0; // The variable that is to be changed
var speed = [4.5, 0, -4.5]; // The acceleration in m/s
var time = [2, 4, 2]; // Duration corresponding to each acceleration in s
var sec = 1000; // 1 second = 1000 milliseconds
var i = 0; // A counter to remember the item number in the arrays
var dur = 0; // A variable to hold the duration for which a particular speed has currently lasted. This variable helps to validate the duration for which the Y is changed.

// The function that holds the logic
function tick() {

  // Checking if duration is equal to or has crossed the user specified duration for the speed
  if(dur >= time[i]*1000){
    // If yes, move on to the next speed and duration
    i++;
    dur = 0;
    if(i > speed.length-1){clearInterval(loop);} // If there are no more items in the array stop the interval
  }
  else {
    // If not, continue increasing Y and dur
    Y = Math.round(Y*1000 + (speed[i]/50)*1000)/1000 // A simple workaround to avoid the error in arthimetic calculation that occurs while using floats (decimal numbers) in JS.
    console.log(Y); // This line is only for debugging purposes. IT CAN BE REMOVED
    dur += sec/50;
  }
}
var loop = setInterval(tick, sec/50);