在Unity中绘制贝塞尔曲线
贝塞尔曲线
包含两个点,起点和终点,所有点是从起点到终点的直线上,也叫一阶贝塞尔曲线
包含三个点,起点,中间调控点,终点,所有点是在起点到终点的一个曲线,通过改变中间控制点来调控每个点的位置,也叫二阶贝塞尔曲线
包含四个点,起点,中间调控点1,中间调控点2,终点,所有点是在起点到终点的一个曲线,通过改变中间调控点1,中间调控点2 来调控每个点的位置,也叫三阶贝塞尔曲线
using UnityEngine;
/// <summary>
/// 贝塞尔曲线
/// t 的取值范围 [0, 1]
/// </summary>
public class Bezier
{
private Vector3 p0;
private Vector3 p1;
private Vector3 p2;
private Vector3 p3;
public Bezier(Vector3 p0, Vector3 p1)
{
this.p0 = p0;
this.p1 = p1;
}
public Bezier(Vector3 p0, Vector3 p1, Vector3 p2)
{
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
}
public Bezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
{
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
// 一阶 Bezier 曲线,使用构造函数 Bezier(Vector3 p0, Vector3 p1) 创建对象,调用 GetPoint1
public Vector3 GetPoint1(float t)
{
return p0 + (p1 - p0) * t;
}
// 二阶 Bezier 曲线,使用构造函数 Bezier(Vector3 p0, Vector3 p1, Vector3 p2) 创建对象,调用 GetPoint2
public Vector3 GetPoint2(float t)
{
float minus = 1 - t;
return p0 * Pow(minus, 2) + 2 * p1 * t * minus + p2 * Pow(t, 2);
}
// 三阶 Bezier 曲线,使用构造函数 Bezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) 创建对象,调用 GetPoint3
public Vector3 GetPoint3 (float t)
{
float minus = 1 - t;
return p0 * Pow(minus, 3) + 3 * p1 * t * Pow(minus, 2) + 3 * p2 * Pow(t, 2) * minus + p3 * Pow(t, 3);
}
private float Pow(float f, float p)
{
return (float)System.Math.Pow(f, p);
}
}
第三步:调用代码如下
Bezier2 bezier2 = new Bezier2(start, point1, end);
for (int i = 0; i < 100; ++i)
{
Vector3 pos = bezier2.GetPoint2(i * 0.01f);
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Capsule);
go.name = i.ToString();
go.transform.localScale = Vector3.one * 0.1f;
go.transform.position = pos;
}