贝塞尔曲线一阶是线性曲线:
公式 : B1(t) = (1-t)* p0 + t* p1 二阶的贝塞尔曲线是建立在一阶的基础上,B2(t) = B1(t) * (1-t) + tB1(t) 化简后可得 : B2(t) = (1 - t) * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p0 + t * p1) 注:一阶是(1-t) * p0 + tp1
c#代码如下所示
public class BezierMath
{
public static Vector3 Bezier_2(Vector3 p0, Vector3 p1, Vector3 p2, float t)
{
return (1 - t) * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p0 + t * p1);
}
public static Vector3 Bezier_3(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
return (1 - t) * (((1 - t) * p0 + t * p1) + t * ((1 - t) * p0 + t * p1)) + t * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p0 + t * p1);
}
public static Vector3 Bezier(List<Vector3> p, float t)
{
if (p.Count < 2)
return p[0];
List<Vector3> list2 = new List<Vector3>();
for (int i = 0; i < p.Count - 1; i++)
{
Vector3 pos = (1 - t) * p[i] + t * p[i + 1];
list2.Add(pos);
}
return Bezier(list2, t);
}
}
public class Test : MonoBehaviour
{
public List<Transform> go;
private List<Vector3> pos = new List<Vector3>();
void Start()
{
for (int i = 0; i < go.Count - 1; i++)
{
pos.Add(go[i].position);
}
}
void Update()
{
for (float i = 0; i < 1; i += 0.1f)
{
Debug.DrawLine(BezierMath.Bezier(pos, i), BezierMath.Bezier(pos, i + 0.1f), Color.blue);
}
}
}
![
运行效果如下:
|