1. 程式人生 > 程式設計 >unity繪製一條流動的弧線(貝塞爾線)

unity繪製一條流動的弧線(貝塞爾線)

本文例項為大家分享了unity繪製一條流動弧線的具體程式碼,供大家參考,具體內容如下

最終效果

unity繪製一條流動的弧線(貝塞爾線)

unity繪製一條流動的弧線(貝塞爾線)

把下面指令碼複製,直接拖上指令碼,設定兩個點(物體)的位置
GameObject1是開始點的位置,GameObject2是結束點的位置

public Transform[] controlPoints;
public LineRenderer lineRenderer;
public float centerPoint =0.1f;

private int layerOrder = 0;
//生成弧線中間的點數
private int _segmentNum = 20;

//偏移
float m_offset;
float m_speed = 0.5f;

void Start()
{
 if (!lineRenderer)
 {
  lineRenderer = GetComponent<LineRenderer>();
 }
 lineRenderer.sortingLayerID = layerOrder;
 //呼叫畫貝斯爾線
 GetBeizerList(controlPoints[0].position,(controlPoints[0].position + controlPoints[1].position) * 0.5f + new Vector3(0,centerPoint,0),controlPoints[1].transform.position,_segmentNum);
}

private void Update()
{
 m_offset = m_offset - m_speed * Time.deltaTime;
 //控制offset使材質移動
 GetComponent<LineRenderer>().material.mainTextureOffset = new Vector2(m_offset,0);
}

/// <summary>
/// 根據T值,計算貝塞爾曲線上面相對應的點
/// </summary>
/// <param name="t"></param>T值
/// <param name="p0"></param>起始點
/// <param name="p1"></param>控制點
/// <param name="p2"></param>目標點
/// <returns></returns>根據T值計算出來的貝賽爾曲線點
private static Vector3 CalculateCubicBezierPoint(float t,Vector3 p0,Vector3 p1,Vector3 p2)
{
 float u = 1 - t;
 float tt = t * t;
 float uu = u * u;

 Vector3 p = uu * p0;
 p += 2 * u * t * p1;
 p += tt * p2;

 return p;
}

/// <summary>
/// 獲取儲存貝塞爾曲線點的陣列
/// </summary>
/// <param name="startPoint"></param>起始點
/// <param name="controlPoint"></param>控制點
/// <param name="endPoint"></param>目標點
/// <param name="segmentNum"></param>取樣點的數量
/// <returns></returns>儲存貝塞爾曲線點的陣列
public Vector3[] GetBeizerList(Vector3 startPoint,Vector3 controlPoint,Vector3 endPoint,int segmentNum)
{
 Vector3[] path = new Vector3[segmentNum];
 for (int i = 1; i <= segmentNum; i++)
 {
  float t = i / (float)segmentNum;
  Vector3 pixel = CalculateCubicBezierPoint(t,startPoint,controlPoint,endPoint);
  //設定lineRenderer的control Points
  lineRenderer.positionCount = i;
  lineRenderer.SetPosition(i - 1,pixel);
  //儲存Point
  path[i - 1] = pixel;
  Debug.Log(path[i - 1]);
 }
 return path;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。