将更改限制为最大金额

时间:2014-03-08 23:20:08

标签: c++ c

说我有:

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

void updateVelocity() // called every 100ms
{
   int limit = 5;
}

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

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

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

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

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

为了做到这一点,必须添加哪些更新功能?

由于

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

我不确定你为什么要尝试使用速度作为整体,但是你走了。

int change_this_frame = targetVelocity - currentVelocity;

if( change_this_frame > 5 )
{
    change_this_frame = 5;
}

if( change_this_frame  < -5 )
{
    change_this_frame = -5;
}

currentVelocity += change_this_frame;

答案 2 :(得分:1)

保持INT_MIN和INT_MAX

的一些工作
#include <limits.h>
int currentVelocity; //can be negative
int targetVelocity; //c

void updateCurrentVelocity() // called every 100ms
{
   int limit = 5;
   int currentVelocityLimit;

   if (targetVelocity > currentVelocity) {
     if (currentVelocity <= INT_MAX - limit) {
       currentVelocityLimit = currentVelocity + limit;
     }
     else {
       currentVelocityLimit = INT_MAX;
     }
     if (currentVelocityLimit > targetVelocity) 
       currentVelocityLimit = targetVelocity;
     currentVelocity = currentVelocityLimit;
   }
   else if (targetVelocity < currentVelocity) {
     if (currentVelocity >= INT_MIN + limit) {
       currentVelocityLimit = currentVelocity - limit;
     }
     else {
       currentVelocityLimit = INT_MIN;
     }
     if (currentVelocityLimit < targetVelocity) 
       currentVelocityLimit = targetVelocity;
     currentVelocity = currentVelocityLimit;
   }
}