天天看點

Unity3D貝塞爾曲線公式 2021-03-24Unity3D貝塞爾曲線公式

Unity3D貝塞爾曲線公式

你可以直接使用CalculateCubicBezierPoint方法,

public class TripleBezier : MonoBehaviour
{
    public Transform[] 擷取四個點_初始_控制A_控制B_終點;
    public LineRenderer 拖拽自身的LineRenderer;

    private int layerOrder = 0;
    //取樣數
    private int _segmentNum = 100;
    void Start()
    {
        if (!拖拽自身的LineRenderer)
        {
            拖拽自身的LineRenderer = GetComponent<LineRenderer>();
        }
        拖拽自身的LineRenderer.sortingLayerID = layerOrder;
    }
    void Update()
    {
        DrawCurve();
    }
    //畫曲線
    void DrawCurve()
    {
        for (int i = 1; i < _segmentNum; i++)
        {
            float t = i / (float)_segmentNum;
            print(t);
            int nodeIndex = 0;
            Vector3 pixel = CalculateCubicBezierPoint(t, 擷取四個點_初始_控制A_控制B_終點[nodeIndex].position, 擷取四個點_初始_控制A_控制B_終點[nodeIndex + 1].position,
                擷取四個點_初始_控制A_控制B_終點[nodeIndex + 2].position, 擷取四個點_初始_控制A_控制B_終點[nodeIndex + 3].position);
            拖拽自身的LineRenderer.positionCount = i;
            拖拽自身的LineRenderer.SetPosition(i - 1, pixel);
        }
    }
    //獲得貝塞爾曲線的數組
    Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
    {
        float u = 1 - t;
        float uu = u * u;
        float uuu = u * u * u;
        float tt = t * t;
        float ttt = t * t * t;
        Vector3 p = p0 * uuu;
        p += 3 * p1 * t * uu;
        p += 3 * p2 * tt * u;
        p += p3 * ttt;
        return p;
    }
}