Unity在两点之间画一条抛物线(缓慢延伸)

    public Transform start;        // 轨迹起点
    public Transform end;          // 轨迹终点
    public float height = 5f;      // 曲线最大高度
    public int segmentCount = 50; // 轨迹分段数(越高越平滑)
    public float lineWidth = 0.1f; // 线条宽度
    private LineRenderer lineRenderer; // 用于绘制曲线的组件

    void Start()
    {
        // 获取或初始化LineRenderer组件
        lineRenderer = GetComponent<LineRenderer>();
        // 设置线条宽度
        lineRenderer.startWidth = lineWidth;
        lineRenderer.endWidth = lineWidth;
        // 设置材质
        lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
        // 设置颜色渐变
        lineRenderer.startColor = Color.blue;
        lineRenderer.endColor = Color.green;
        // 设置轨迹点数量
        lineRenderer.positionCount = segmentCount + 1;
        StartCoroutine(AnimateCurve());

    }
    //private void Update()
    //{
    //    // 当起点或终点移动时自动更新曲线(动态更新)
    //    if (start.hasChanged || end.hasChanged)
    //    {
    //        DrawCurve();
    //        start.hasChanged = end.hasChanged = false;
    //    }
    //}

    //慢慢延伸的曲线(固定起点与终点)
    IEnumerator AnimateCurve()
    {
        lineRenderer.positionCount = 0;
        for (int i = 0; i <= segmentCount; i++)
        {
            lineRenderer.positionCount = i + 1;
            float t = i / (float)segmentCount;
            Vector3 point = Vector3.Lerp(start.position, end.position, t);
            point.y += height * Mathf.Sin(t * Mathf.PI);
            lineRenderer.SetPosition(i, point);
            yield return new WaitForSeconds(0.03f);
        }
    }

    void DrawCurve()
    {
        Vector3 startPos = start.position;
        Vector3 endPos = end.position;     
        // 生成每个轨迹点
        for (int i = 0; i <= segmentCount; i++)
        {
            float t = i / (float)segmentCount; // 插值比例 [0,1]
            // 使用正弦函数模拟高度变化(非标准抛物线)
            //float y = height * Mathf.Sin(t * Mathf.PI);
            // 标准抛物线方程
            float y = height * 4 * t * (1 - t); 
            // 线性插值基础位置 + 高度偏移
            Vector3 point = Vector3.Lerp(startPos, endPos, t);
            point.y += y;
            // 设置线段点位置
            lineRenderer.SetPosition(i, point);
        }
    }
}

bezierLine

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值