Unity基于lineRenderer和贝塞尔曲线绘制平滑线条

目录

前言

1.调用方式

2.代码示例

实现效果


前言

在unity当中,现在需要根据控制点生成一段可闭合的,平滑曲线,并使用linerenderer绘制出来

1.调用方式

代码如下(示例):传入一个控制点列表,和lineRenderer组件

DrawBezierCurve(posList, lineRender);

2.代码示例

/// <summary>
/// 根据控制点生成对应的贝塞尔曲线
/// </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;
}

实现效果

猜你喜欢

转载自blog.csdn.net/crb114594/article/details/130359389
今日推荐