天天看點

留個檔,Unity自定義曲線,Unity畫曲線,貝塞爾曲線

網上有很多貝塞爾曲線實作原理,這篇給自己留個檔,好用就行。

using UnityEngine;

public class BezierCurve: MonoBehaviour
{
    /// <summary>
    /// 曲線上的點數量;
    /// </summary>
    [SerializeField] int m_nPointCount = 50;
    [SerializeField] Transform[] m_arrTransDocks = null;

    /// <summary>
    /// 計算結果;
    /// </summary>
    private Vector3[] m_arrResultPoints = null;

    public Vector3[] MathPathPoints()
    {
        int nCount = m_arrTransDocks.Length;
        Vector3[] m_arrDockPoints = new Vector3[nCount];
        for (int i = 0; i < nCount; i++)
        {
            m_arrDockPoints[i] = m_arrTransDocks[i].position;
        }

        m_arrResultPoints = new Vector3[m_nPointCount];
        for (int i = 0; i < m_nPointCount; i++)
        {
            Vector3[] temp1 = m_arrDockPoints;
            for (int j = temp1.Length - 1; j > 0; j--)
            {
                Vector3[] temp2 = new Vector3[j];
                for (int k = 0; k < j; k++)
                {
                    temp2[k] = Vector3.Lerp(temp1[k], temp1[k + 1], i / (float)m_nPointCount);
                }
                temp1 = temp2;
            }
            m_arrResultPoints[i] = temp1[0];
        }
        return m_arrResultPoints;
    }

#if UNITY_EDITOR
    void OnDrawGizmos()
    {
        MathPathPoints();
        if (m_arrResultPoints != null && m_arrResultPoints.Length > 0)
        {
            Gizmos.color = Color.yellow;
            for (int i = 0; i < m_arrResultPoints.Length - 1; i++)
            {
                Gizmos.DrawLine(m_arrResultPoints[i], m_arrResultPoints[i + 1]);
            }
        }
    }
#endif
}

           

程式學無止盡。

歡迎大家溝通,有啥不明确的,或者不對的,也可以和我私聊

我的QQ 334524067 神一般的狄狄

繼續閱讀