您正在对运动进行离散时间模拟。保持简单的一种方法是以使加速和减速对称的方式执行计算。换句话说,加速时行驶的距离应该与减速时行驶的距离相同。例如,假设
- 加速度为5
- 最高速度为13
- 物体一达到最高速度就开始减速
以下是离散时间模拟的进展方式
first tick
old speed = 0
new speed = 5
distance = 5
second tick
old speed = 5
new speed = 10
distance = 15
third tick
old speed = 10
new speed = 13
distance = 28 <-- total distance while accelerating
fourth tick
old speed = 13
distance = 41
new speed = 10 <-- not 8!!!
fifth tick
old speed = 10
distance = 51
new speed = 5
sixth tick
old speed = 5
distance = 56 <-- Yay, twice the distance, we have symmetry
new speed = 0
这里有两个关键点
- 加速时先更新速度,再更新距离。减速时顺序相反,先更新距离,再更新速度。
- 减速时,将调整后的速度保持为加速度的倍数很重要
在 C 编程语言中,以下代码可用于在减速期间更新速度
if ( old_speed % acceleration != 0 ) // if speed is not a multiple of acceleration
new_speed = old_speed - old_speed % acceleration; // reduce speed to a multiple of acceleration
else // otherwise
new_speed = old_speed - acceleration; // reduce speed by acceleration
如果加速和减速是对称的,那么计算减速距离与计算加速距离是一样的。
distance = acceleration * (1+2+3+ ... +N) + fudge_factor
在哪里
N
被top_speed / acceleration
截断为整数,例如13/5 ==> 2
fudge_factor
是0
如果最高速度是加速度的倍数,
top_speed
否则
计算可以简化为
1+2+3+ ... +N = N * (N+1) / 2
在 C 中,减速时行进的总距离可以计算如下
int top_speed = 13;
int acceleration = 5;
int N = top_speed / acceleration; // Note: in C, integer division truncates
int fudge = 0;
if ( top_speed % acceleration != 0 )
fudge = top_speed;
int distance = acceleration * (N * (N+1)) / 2 + fudge;