Search code examples
algorithmunity-game-enginelinesmoothing

Unity line renderer smooth algorithm


I need an !effective! algorithm to smooth a line renderer (basically, the given Vector3 which holds the points of the renderer)

something like that enter image description here Here is my code, but the fps with it is very low:

public static List<Vector3> MakeSmoothCurve(Vector3[] arrayToCurve, float smoothness)
{
    List<Vector3> points;
    List<Vector3> curvedPoints;
    int pointsLength = 0;
    int curvedLength = 0;

    if (smoothness < 1.0f) smoothness = 1.0f;

    pointsLength = arrayToCurve.Length;

    curvedLength = (pointsLength * Mathf.RoundToInt(smoothness)) - 1;
    curvedPoints = new List<Vector3>(curvedLength);

    float t = 0.0f;
    for (int pointInTimeOnCurve = 0; pointInTimeOnCurve < curvedLength + 1; pointInTimeOnCurve++)
    {
        t = Mathf.InverseLerp(0, curvedLength, pointInTimeOnCurve);

        points = new List<Vector3>(arrayToCurve);

        for (int j = pointsLength - 1; j > 0; j--)
        {
            for (int i = 0; i < j; i++)
            {
                points[i] = (1 - t) * points[i] + t * points[i + 1];
            }
        }

        curvedPoints.Add(points[0]);
    }

    return (curvedPoints);
}

Solution

  • You can use a CurveField

    https://docs.unity3d.com/ScriptReference/EditorGUILayout.CurveField.html

    With that you can easily edit/test your curve and retrieve a point at given time.

    https://docs.unity3d.com/ScriptReference/AnimationCurve.Evaluate.html