Unity3d 用递归方式求Bezier贝赛尔曲线

 public List objs;
    [Range(0,1)]
    public float t;

    public GameObject move;

    private void OnDrawGizmos()
    {

        List poslist = objs.Select(x => x.transform.position).ToList();
        lines.Clear();
        move.transform.position = Bezier(poslist,t);
        foreach(var ml in lines)
        {
            Gizmos.DrawLine(ml.p1, ml.p2);
        }
    }

    public struct MyLine
    {
        public Vector3 p1;
        public Vector3 p2;
        public MyLine(Vector3 p1,Vector3 p2)
        {
            this.p1 = p1;
            this.p2 = p2;
        }
    }
    public List lines = new List();

    public Vector3 Bezier(List posList, float t)
    {
        if (posList.Count < 2) return Vector3.zero;
        if (posList.Count == 2)
        {

            lines.Add(new MyLine(posList[0], posList[1]));
            return Vector3.Lerp(posList[0], posList[1], t);
        }
        List newPosList = new List();
        for (int i = 1; i < posList.Count; i++)
        {
            newPosList.Add(Vector3.Lerp(posList[i - 1], posList[i], t));
            lines.Add(new MyLine(posList[i - 1], posList[i]));
        }
        return Bezier(newPosList, t);
    }

Unity3d 用递归方式求Bezier贝赛尔曲线_第1张图片

你可能感兴趣的:(C#,Unity,unity,C#脚本)