【Unity】计算并绘制贝塞尔曲线
直接代码贴上,场景中随意创建一个空对象,挂载上此脚本即可在Scene窗口查看效果,注意打开Gizmos显示。

通过调整参数改变贝塞尔曲线的绘制精度和初始锚点,可查看 N 阶贝塞尔曲线效果。
高阶算法通过递归实现,消耗较大,但易于理解。
前三阶算法使用最原始的贝塞尔曲线逻辑,效率高而且理解十分轻松。
二阶或三阶贝塞尔曲线即可满足一般需求。
using System.Collections.Generic;
using UnityEngine;
public class Bezier : MonoBehaviour
{
// 贝塞尔曲线的精准度,绘制点的个数
[SerializeField] private int iPointsCount = 100;
// 贝塞尔曲线锚点取值,n 阶贝塞尔曲线需要 n+1 个锚点
[SerializeField] private List<Vector3> pAnchors = new List<Vector3>(
new Vector3[] { Vector3.up, Vector3.zero, Vector3.right });
// 贝塞尔曲线绘制点
private List<Vector3> pPoints = new List<Vector3>();
// 一般二阶或三阶的贝塞尔曲线就可以满足需求,考虑算法性能,前三阶计算不使用递归算法
// 获取一阶贝塞尔曲线绘制点位置
private void GetPointsLevel1()
{
pPoints.Clear();
for (int i = 0; i <= iPointsCount; ++i)
pPoints.Add(Vector3.Lerp(pAnchors[0], pAnchors[1], (float)i / iPointsCount));
}
// 获取二阶贝塞尔曲线绘制点位置
private void GetPointsLevel2()
{
pPoints.Clear();
for(int i = 0; i <= iPointsCount; ++i)
{
Vector3 newAnchor1 = Vector3.Lerp(pAnchors[0], pAnchors[1], (float)i / iPointsCount);
Vector3 newAnchor2 = Vector3.Lerp(pAnchors[1], pAnchors[2], (float)i / iPointsCount);
pPoints.Add(Vector3.Lerp(newAnchor1, newAnchor2, (float)i / iPointsCount));
}
}
// 获取三阶贝塞尔曲线绘制点位置
private void GetPointsLevel3()
{
pPoints.Clear();
for(int i = 0; i <= iPointsCount; ++i)
{
Vector3 newAnchor1 = Vector3.Lerp(pAnchors[0], pAnchors[1], (float)i / iPointsCount);
Vector3 newAnchor2 = Vector3.Lerp(pAnchors[1], pAnchors[2], (float)i / iPointsCount);
Vector3 newAnchor3 = Vector3.Lerp(pAnchors[2], pAnchors[3], (float)i / iPointsCount);
Vector3 newNewAnchor1 = Vector3.Lerp(newAnchor1, newAnchor2, (float)i / iPointsCount);
Vector3 newNewAnchor2 = Vector3.Lerp(newAnchor2, newAnchor3, (float)i / iPointsCount);
pPoints.Add(Vector3.Lerp(newNewAnchor1, newNewAnchor2, (float)i / iPointsCount));
}
}
// 递归获取 N 阶贝塞尔曲线绘制点位置
// 与前三阶类似,把绘制点一一计算并保存
private void GetPointsRecursion()
{
pPoints.Clear();
for (int i = 0; i <= iPointsCount; ++i)
pPoints.Add(GetPointRecursion((float)i / iPointsCount, pAnchors));
}
// 递归计算每一个绘制点位置,t 是绘制点的插值比例
private Vector3 GetPointRecursion(float t, List<Vector3> anchors)
{
if (anchors.Count <= 1)
return anchors[0];
List<Vector3> newAnchors = new List<Vector3>();
for (int i = 0; i < anchors.Count - 1; ++i)
newAnchors.Add(Vector3.Lerp(anchors[i], anchors[i + 1], t));
return GetPointRecursion(t, newAnchors);
}
// 根据锚点数选择合适算法计算贝塞尔曲线绘制点
private void GetBezierPoints()
{
pPoints.Clear();
if (pAnchors == null || pAnchors.Count <= 1)
return;
switch (pAnchors.Count - 1)
{
case 1:
GetPointsLevel1();
break;
case 2:
GetPointsLevel2();
break;
case 3:
GetPointsLevel3();
break;
default:
GetPointsRecursion();
break;
}
}
// 简单写一个Gizmos绘制函数检验算法
private void OnDrawGizmos()
{
GetBezierPoints();
Gizmos.color = new Color(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f), Random.Range(0.5f, 1f));
for(int i = 0; i < iPointsCount; ++i)
{
Gizmos.DrawLine(pPoints[i], pPoints[i + 1]);
Gizmos.DrawSphere(pPoints[i], 0.1f);
}
}
}
3785




被折叠的 条评论
为什么被折叠?



