贝塞尔曲线的算法网上有很多讲的很细的教程,本文只记录下容易用到的二维三维曲线的直接使用,属于傻瓜式操作,用得到的自取。
二维贝塞尔曲线:
void DrawCurve()
{//SEGMENT_COUNT 曲线内坐标点数 越多越平滑
for (int i = 1; i <= SEGMENT_COUNT; i++)
{
float t = i / (float)SEGMENT_COUNT;
int nodeIndex = 0;
Vector3 pixel = CalculateCubicBezierPoint(t, pos[nodeIndex],
pos[nodeIndex + 1], pos[nodeIndex + 2]);
lineRenderer.positionCount = i;
lineRenderer.SetPosition(i - 1, pixel);
}
}
/// <summary>
/// 贝塞尔算法
/// </summary>
/// <param name="t"></param>
/// <param name="p0">坐标1</param>
/// <param name="p1">坐标2</param>
/// <param name="p2">坐标3</param>
/// <returns></returns>
Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2)
{
float u = 1 - t;
float tt = t * t;
float uu = u * u;
Vector3 p = uu * p0;
p += 2 * u * t * p1;
p += tt * p2;
return p;
}
三维贝塞尔曲线:
void DrawCurve()
{
for (int j = 0; j < curveCount; j++)
{
for (int i = 1; i <= SEGMENT_COUNT; i++)
{
float t = i / (float)SEGMENT_COUNT;
int nodeIndex = j * 3;
Vector3 pixel = CalculateCubicBezierPoint(t, pos[nodeIndex], pos[nodeIndex + 1], pos[nodeIndex + 2], pos[nodeIndex + 3]);
lineRenderer.positionCount = (((j * SEGMENT_COUNT) + i));
lineRenderer.SetPosition((j * SEGMENT_COUNT) + (i - 1), pixel);
}
}
}
Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
{
float u = 1 - t;
float tt = t * t;
float uu = u * u;
float uuu = uu * u;
float ttt = tt * t;
Vector3 p = uuu * p0;
p += 3 * uu * t * p1;
p += 3 * u * tt * p2;
p += ttt * p3;
return p;
}
有用的话,请点赞~