Tabla de contenido
prefacio
En Unity, ahora es necesario generar una curva suave y cerrada basada en los puntos de control y dibujarla usando linerenderer
1. Método de llamada
El código es el siguiente (ejemplo): pase una lista de puntos de control y el componente lineRenderer
DrawBezierCurve(posList, lineRender);
2. Ejemplo de código
/// <summary> /// 根据控制点生成对应的贝塞尔曲线 /// </summary> /// <param name="positions"></param> /// <param name="lineRenderer "></param> private void DrawBezierCurve(List<Vector3> posiciones, LineRenderer lineRenderer) { if (positions.Count < 2) { return; } var partCount = 20; renderizadordelineas.positionCount = 0; lineRenderer.positionCount = (posiciones.Count - 1) * partCount ; for (int i = 0; i < posiciones.Cuenta - 1; i++) { Vector3 p0 = i == 0 ? posiciones[0] : posiciones[i - 1]; Vector3 p1 = posiciones[i]; Vector3 p2 = posiciones[i + 1]; Vector3 p3 = i == posiciones.Cuenta - 2 ? posiciones[posiciones.Cuenta - 1] : posiciones[i + 2]; for (int j = 0; j < partCount; j++) { var t = (float)j / partCount; Vector3 punto = CalculateCatMullRomPoint(t, p0, p1, p2, p3); renderizadordelineas.SetPosition(i * partCount + j, punto); } } } /// <summary> /// 计算CatMullRomPoint /// </summary> /// <param name="t"></param> /// <param name="p0"></param > /// <param nombre="p1"></param> /// <param nombre="p2"></param> /// <param nombre="p3"></param> /// < devoluciones></devoluciones> privado Vector3 CalculateCatMullRomPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) { float t2 = t * t; flotante t3 = t2 * t; Vector3 punto = 0.5f * ((2f * p1) + (-p0 + p2) * t + (2f * p0 - 5f * p1 + 4f * p2 - p3) * t2 + (-p0 + 3f * p1 - 3f * p2 + p3) * t3); punto de retorno; }
lograr efecto