浅析:贝塞尔曲线

贝塞尔曲线

image

一句话概括就是计算两两点之间的差值,同理高阶贝塞尔就在计算完给定点两两插值后,再计算插值的插值,直到被计算点数量为一

using System.Collections.Generic;
using UnityEngine;

public class BezierTest : MonoBehaviour
{
    public Transform startPoint;
    public Transform endPoint;
    public Transform target;
    public Transform steinerPoint;
    public float speed;
    private float timer;

    private List<Vector3> runningPoints;
    private float distance;

    // Start is called before the first frame update
    void Start()
    {
        runningPoints = new List<Vector3>();
        target.position = startPoint.position;
        distance = Vector3.Distance(startPoint.position, endPoint.position);
    }

    Vector3 BezierCurve(float f)
    {
        runningPoints.Clear();
        runningPoints.Add(startPoint.position);
        for (int i = 0; i < steinerPoint.childCount; i++)
        {
            runningPoints.Add(steinerPoint.GetChild(i).position);
        }
        runningPoints.Add(endPoint.position);

        int num = runningPoints.Count;
        while (num > 1)
        {
            for (int i = 0; i < num - 1; i++)
            {
                Debug.DrawLine(runningPoints[i], runningPoints[i + 1], Color.red);
                runningPoints[i] = Vector3.Lerp(runningPoints[i], runningPoints[i + 1], f);
            }
            --num;
        }
        return runningPoints[0];
    }

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        target.position = BezierCurve(timer * speed / distance);
    }
}

image

posted @ 2023-04-05 16:50  有间猫  阅读(46)  评论(0编辑  收藏  举报