从点数组生成平滑曲线并让实体沿曲线运动的方法
数据小陈
结论:可以。比较常用、实现成本也低的方式,是用 Catmull-Rom 样条把点数组变成一条经过各点的分段平滑曲线,再做弧长参数化,让 entity 按固定速度沿曲线移动。Bézier 曲线也能实现,可选的方案不止这一种。
可选曲线方案
- Catmull-Rom / centripetal Catmull-Rom:曲线会经过给定点,适合做关卡轨迹;centripetal 版本能减少尖点和过冲。
- 分段三次 Bézier:需要额外控制点,适合手工调形状;如果直接拿点数组来用,需要自己推导控制点。
- B-spline / 自然三次样条:B-spline 通常不会严格经过给定点,自然样条能过点,但端点处理要小心。
- Chaikin 或折线圆角:实现简单,适合只要求视觉平滑、不要求数学上光滑的场合。
实现步骤
- 用
struct position array[num_points]保存路径点;再把端点复制一份,方便 Catmull-Rom 处理首尾段。 - 对每段
P1 -> P2,用P0,P1,P2,P3采样,得到密集的折线点,或者直接保存曲线参数。 - 建立弧长表:按采样点累计距离,记录每一段的起止长度。
- 跟随阶段维护
traveledDistance,每帧加上speed * dt,再在弧长表里查位置;切线可以用前后采样点之差或曲线导数求,供朝向和速度方向使用。 - 将结果写入 entity 的
p、v、a。如果物理系统会自己积分,建议把曲线输出当作目标速度或转向约束,不要每帧硬改位置,避免和碰撞、加速度逻辑冲突。
C 代码示例:Catmull-Rom 采样与弧长查表
#include <math.h>
struct position { double x; double y; };
static struct position catmull_rom(struct position p0, struct position p1,
struct position p2, struct position p3,
double t) {
double t2 = t * t;
double t3 = t2 * t;
struct position r;
r.x = 0.5 * ((2.0 * p1.x) +
(-p0.x + p2.x) * t +
(2.0 * p0.x - 5.0 * p1.x + 4.0 * p2.x - p3.x) * t2 +
(-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t3);
r.y = 0.5 * ((2.0 * p1.y) +
(-p0.y + p2.y) * t +
(2.0 * p0.y - 5.0 * p1.y + 4.0 * p2.y - p3.y) * t2 +
(-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t3);
return r;
}
#define SAMPLES_PER_SEG 32
// 简化示例:返回按弧长比例采样的位置;实际项目建议预计算路径表
struct position sample_path(struct position pts[], int n, double u) {
// u: 0..1 的路径进度;这里没有做弧长重参数化,仅示意插值调用
double f = u * (n - 1);
int i = (int)f;
if (i >= n - 1) i = n - 2;
double t = f - i;
struct position p0 = pts[i > 0 ? i - 1 : 0];
struct position p1 = pts[i];
struct position p2 = pts[i + 1];
struct position p3 = pts[i + 2 < n ? i + 2 : n - 1];
return catmull_rom(p0, p1, p2, p3, t);
}
上面只是插值骨架。要让实体匀速跟随,不能直接对整条曲线的 u 均匀取值。应先按 SAMPLES_PER_SEG 采样并累计弧长,再根据目标距离查表。伪代码如下:
// 预计算:path[i] 是采样点,len[i] 是到 path[i] 的累计长度
// 每帧:
traveled += speed * dt;
if (traveled >= totalLength) traveled -= totalLength; // 或停止/循环
int idx = upper_bound(len, traveled); // 找到所在区间
double local = (traveled - len[idx - 1]) / (len[idx] - len[idx - 1]);
struct position pos = lerp(path[idx - 1], path[idx], local);
struct position tangent = sub(path[idx], path[idx - 1]);
normalize(&tangent);
entity.p = pos;
entity.v.x = tangent.x * speed;
entity.v.y = tangent.y * speed;
注意事项
- 如果轨迹必须严格经过每个给定点,选 Catmull-Rom 或自然三次样条;如果只要求整体形状接近点列,B-spline 也可以。
- 点距变化大时,普通 Catmull-Rom 容易过冲,优先考虑 centripetal Catmull-Rom。
- 2D 射击游戏里常需要循环轨迹。首尾点相同时,把端点索引做环绕处理,循环处才不会有速度突变。
- 直接设置
entity.p会让物理积分失效;如果实体有加速度和碰撞,最好把曲线采样点作为转向目标,用速度或加速度逐步逼近。
备注:内容仅供参考。
