2

我正在尝试从 Unity 中的点列表生成 Catmull-Rom 曲线。因为我不想在曲线的点之间存储点,所以我选择使用一种可以根据时间计算 Catmull-Rom 曲线中的位置的解决方案。这里这里有一些这样的例子,但是,它们都没有展示如何实现 alpha。

我想实现 alpha 的原因是我可以在向心曲线、弦曲线和统一的 Catmull-Rom 曲线之间切换。

private Vector3 GetCatmullRomPosition(float t, Vector3 p0, Vector3 p1,
                                      Vector3 p2, Vector3 p3, float alpha)
{
    Vector3 a = 2f * p1;
    Vector3 b = p2 - p0;
    Vector3 c = 2f * p0 - 5f * p1 + 4f * p2 - p3;
    Vector3 d = -p0 + 3f * p1 - 3f * p2 + p3;
    return 0.5f * (a + (b * t) + (c * t * t) + (d * t * t * t));
}

代码来源

4

1 回答 1

2

对于任何来到这里的人来说,答案实际上来自原始问题的一个链接中的数学。这是一个SO question Catmull-rom curve with no cusps and no self-intersections 的答案。所以归功于cfh

在我的原始问题中发布的代码是计算统一 Catmull-Rom 样条中的点的好方法,但是,它没有考虑 alpha。因此,它不能用于弦线或向心线,(或介于两者之间的任何东西)Catmull-Rom 样条。下面的代码确实考虑了 alpha,因此支持弦和向心 Catmull-Rom 样条。

事不宜迟,这里是移植到 C# for Unity 的代码。

private Vector3 GetCatmullRomPosition(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float alpha = 0.5f)
{
    float dt0 = GetTime(p0, p1, alpha);
    float dt1 = GetTime(p1, p2, alpha);
    float dt2 = GetTime(p2, p3, alpha);

    Vector3 t1 = ((p1 - p0) / dt0) - ((p2 - p0) / (dt0 + dt1)) + ((p2 - p1) / dt1);
    Vector3 t2 = ((p2 - p1) / dt1) - ((p3 - p1) / (dt1 + dt2)) + ((p3 - p2) / dt2);

    t1 *= dt1;
    t2 *= dt1;

    Vector3 c0 = p1;
    Vector3 c1 = t1;
    Vector3 c2 = (3 * p2) - (3 * p1) - (2 * t1) - t2;
    Vector3 c3 = (2 * p1) - (2 * p2) + t1 + t2;
    Vector3 pos = CalculatePosition(t, c0, c1, c2, c3);

    return pos;
}

private float GetTime(Vector3 p0, Vector3 p1, float alpha)
{
    if(p0 == p1)
        return 1;
    return Mathf.Pow((p1 - p0).sqrMagnitude, 0.5f * alpha);
}

private Vector3 CalculatePosition(float t, Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3)
{
    float t2 = t * t;
    float t3 = t2 * t;
    return c0 + c1 * t + c2 * t2 + c3 * t3;
}
于 2018-06-02T21:11:53.313 回答