之前寫了個插件,有個需要曲線插值的功能。給定一些點的位置,物體成一條平滑曲線依次通過這些點。
Bezier曲線是在Unity里比較常用的,但是不適合這里的需求。因為Bezier無法通過所有的點,它需要有另外的點來構造切線。如下圖:
圖1

Bezeir
查了資料發現CatmullRom曲線可以平滑的通過所有點,滿足需求,如下圖:
圖2

CatmullRom
可以看這里的介紹。
在Unity中C#腳本的實現:
/// <summary> /// Catmull-Rom 曲線插值 /// </summary> /// <param name="p0"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <param name="t">0-1</param> /// <returns></returns> Vector3 CatmullRomPoint(Vector3 P0, Vector3 P1, Vector3 P2, Vector3 P3, float t) { float factor = 0.5f; Vector3 c0 = P1; Vector3 c1 = (P2 - P0) * factor; Vector3 c2 = (P2 - P1) * 3f - (P3 - P1) * factor - (P2 - P0) * 2f * factor; Vector3 c3 = (P2 - P1) * -2f + (P3 - P1) * factor + (P2 - P0) * factor; Vector3 curvePoint = c3 * t * t * t + c2 * t * t + c1 * t + c0; return curvePoint; }
需要注意的是,接受參數p0-p3四個點后,所得的曲線為p1和p2之間的。所以要得到多個點構造的曲線,首位部分需要特殊處理下,比如:CatmullRomPoint(p0,p1,p2,p3,t);
這樣可以得到p1和p2之間的曲線。
在Unity中繪制出來:

CatmullRom-Unity
作者:梁先生呀
鏈接:https://www.jianshu.com/p/5cc76b78acb1
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。