首先,让我们创建一个三次 Hermite 样条函数:
/*
t - in interval <0..1>
p0 - Start position
p1 - End position
m0 - Start tangent
m1 - End tangent
*/
double CubicHermite(double t, double p0, double p1, double m0, double m1) {
t2 = t*t;
t3 = t2*t;
return (2*t3 - 3*t2 + 1)*p0 + (t3-2*t2+t)*m0 + (-2*t3+3*t2)*p1 + (t3-t2)*m1;
}
现在您的任务是计算缓入和缓出部分的 p0、p1、m0 和 m1。让我们添加一些变量以使数学更容易编写:
double Interpolate(
double timeToAccel, double timeCruising, double timeToDecel,
double finalPosition,
double currentTime) {
double t1 = timeToAccel;
double t2 = timeCruising;
double t3 = timeToDecel;
double x = finalPosition;
double t = currentTime;
我们需要指定对象在停止加速并开始减速时应该在哪里。您可以随心所欲地指定这些并且仍然产生平滑的运动,但是,我们想要一个有点“自然”的解决方案。
假设巡航速度为v
。在巡航期间,物体移动距离x2 = v * t2
。现在,当物体从 0 加速到速度 v 时,它的行进距离为x1 = v * t1 / 2
。减速也一样x3 = v * t3 / 2
。放在一起:
x1 + x2 + x3 = x
v * t1 / 2 + v * t2 + v * t3 / 2 = x
由此我们可以计算出我们的速度和距离:
double v = x / (t1/2 + t2 + t3/2);
double x1 = v * t1 / 2;
double x2 = v * t2;
double x3 = v * t3 / 2;
现在我们知道了一切,我们只需将其输入三次 Hermite 样条插值器
if(t <= t1) {
// Acceleration
return CubicHermite(t/t1, 0, x1, 0, v*t1);
} else if(t <= t1+t2) {
// Cruising
return x1 + x2 * (t-t1) / t2;
} else {
// Deceleration
return CubicHermite((t-t1-t2)/t3, x1+x2, x, v*t3, 0);
}
}
我在 Excel 中对此进行了测试,这是可以使用的等效 VBA 代码。边界条件有一些除以零,我将此作为练习留给读者
Public Function CubicHermite(t As Double, p0 As Double, p1 As Double, _
m0 As Double, m1 As Double) As Double
t2 = t * t
t3 = t2 * t
CubicHermite = (2 * t3 - 3 * t2 + 1) * p0 + _
(t3 - 2 * t2 + t) * m0 + (-2 * t3 + 3 * t2) * p1 + (t3 - t2) * m1
End Function
Public Function Interpolate(t1 As Double, t2 As Double, t3 As Double, _
x As Double, t As Double) As Double
Dim x1 As Double, x2 As Double, x3 As Double
v = x / (t1 / 2 + t2 + t3 / 2)
x1 = v * t1 / 2
x2 = v * t2
x3 = v * t3 / 2
If (t <= t1) Then
Interpolate = CubicHermite(t / t1, 0, x1, 0, v*t1)
ElseIf t <= t1 + t2 Then
Interpolate = x1 + x2 * (t - t1) / t2
Else
Interpolate = CubicHermite((t-t1-t2)/t3, x1+x2, x, v*t3, 0)
End If
End Function