将更改限制为最大金额

jma*_*erx -2 c c++

说我有:

int currentVelocity; //can be negative
int targetVelocity; //can also be negative

void updateVelocity() // called every 100ms
{
   int limit = 5;
}
Run Code Online (Sandbox Code Playgroud)

如何在每次迭代时使速度更接近目标速度,最大绝对变化为5?

假设我当前的速度为-20,目标速度为-26

我的最大绝对值增加为5.

首次调用updateVelocity()时,currentVelocity再次调用时变为-25,currentVelocity为-26

除非目标速度发生变化,否则将永远如此.

必须添加到更新功能才能执行此操作?

谢谢

Gas*_*ssa 5

一种直截了当的方式.

int currentVelocity; //can be negative
int targetVelocity; //can also be negative

void updateVelocity() // called every 100ms
{
   int limit = 5;
   int delta = targetVelocity - currentVelocity;

   if (delta > limit)
        currentVelocity += limit;
   else if (delta < -limit)
        currentVelocity -= limit;
   else
        currentVelocity = targetVelocity;
}
Run Code Online (Sandbox Code Playgroud)