Table of contents
foreword
In unity, it is now necessary to generate a closed, smooth curve based on the control points and draw it using linerenderer
1. Call method
The code is as follows (example): pass in a list of control points, and the lineRenderer component
DrawBezierCurve(posList, lineRender);
2. Code example
/// <summary> /// Generate the corresponding Bezier curve according to the control points /// </summary> /// <param name="positions"></param> /// <param name="lineRenderer "></param> private void DrawBezierCurve(List<Vector3> positions, LineRenderer lineRenderer) { if (positions.Count < 2) { return; } var partCount = 20; lineRenderer.positionCount = 0; lineRenderer.positionCount = (positions. Count - 1) * partCount ; for (int i = 0; i < positions.Count - 1; i++) { Vector3 p0 = i == 0 ? positions[0] :positions[i - 1]; Vector3 p1 = positions[i]; Vector3 p2 = positions[i + 1]; Vector3 p3 = i == positions.Count - 2 ? positions[positions.Count - 1] : positions[i + 2]; for (int j = 0; j < partCount; j++) { var t = (float)j / partCount; Vector3 point = CalculateCatMullRomPoint(t, p0, p1, p2, p3); lineRenderer.SetPosition(i * partCount + j, point); } } } /// <summary> /// 计算CatMullRomPoint /// </summary> /// <param name="t"></param> /// <param name="p0"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <returns></returns> private Vector3 CalculateCatMullRomPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) { float t2 = t * t; float t3 = t2 * t; Vector3 point = 0.5f * ((2f * p1) + (-p0 + p2) * t + (2f * p0 - 5f * p1 + 4f * p2 - p3) * t2 + (-p0 + 3f * p1 - 3f * p2 + p3) * t3); return point; }
achieve effect