ps:博客從typecho換成jekyll后,文章復(fù)制到簡書來因為圖片鏈接原因變得麻煩了。- -!
正文
之前寫了個插件,有個需要曲線插值的功能。給定一些點的位置,物體成一條平滑曲線依次通過這些點。
Bezier曲線是在Unity里比較常用的,但是不適合這里的需求。因為Bezier無法通過所有的點,它需要有另外的點來構(gòu)造切線。如下圖:
圖1

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

CatmullRom
可以看這里的介紹。
在Unity中C#腳本的實現(xiàn):
/// <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>
public static Vector3 CatmullRomPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
return p1 + (0.5f * (p2 - p0) * t) + 0.5f * (2f * p0 - 5f * p1 + 4f * p2 - p3) * t * t +
0.5f * (-p0 + 3f * p1 - 3f * p2 + p3) * t * t * t;
}
需要注意的是,接受參數(shù)p0-p3四個點后,所得的曲線為p1和p2之間的。所以要得到多個點構(gòu)造的曲線,首位部分需要特殊處理下,比如:CatmullRomPoint(p0,p0,p1,p2,t); 這樣可以得到p0和p1之間的曲線。
在Unity中繪制出來:

CatmullRom-Unity