三阶贝塞尔曲线:B(t) = P0(1 - t)^3 + 3P1t(1 - t)^2 + 3P2t^2(1 - t) + p3t^3,t∈[0, 1];
1.在场景中创建空物体,添加LineRender组件
2.在物体上挂在自己写的脚本 BezierCurve.cs
3.大功告成
PS:如果发现创建的线段丢失材质,可以新建一个默认材质球,拖拽给Linerender组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BezierCurve : MonoBehaviour
{
private LineRenderer lineRenderer;
private Vector3 p0;
private Vector3 p1;
private Vector3 p2;
private Vector3 result;
private List<Vector3> resultList = new List<Vector3>();
private float time = 0;
private float timeLerp;
private float maxTime = 1f;
void Start()
{
lineRenderer = gameObject.GetComponent<LineRenderer>();
lineRenderer.startColor = new Color(1f, 1f, 0f, 0.5f);
lineRenderer.endColor = new Color(0f, 1f, 1f, 0.5f);
lineRenderer.startWidth = 0.02f;
lineRenderer.endWidth = 0.02f;
//如果想在Editor中手动打点,可以使用这个代码块。否则注释这三行,使用下面被注释的代码块。
p0 = lineRenderer.GetPosition(0);
p1 = lineRenderer.GetPosition(1);
p2 = lineRenderer.GetPosition(2);
//p0 = new Vector3(-5, 0, 0);
//p1 = new Vector3(0, 5, 0);
//p2 = new Vector3(5, 0, 0);
}
void FixedUpdate()
{
if (time > maxTime)
{
return;
}
CalculatePosition();
lineRenderer.positionCount = resultList.ToArray().Length;
if (lineRenderer.positionCount >= 2)
{
lineRenderer.SetPositions(resultList.ToArray());
}
}
void CalculatePosition()
{
result = new Vector3();
timeLerp = Mathf.Lerp(0, 1, time / maxTime);
result.x = Mathf.Pow(1 - timeLerp, 2) * p0.x + 2 * timeLerp * Mathf.Pow(1 - timeLerp, 1) * p1.x + Mathf.Pow(timeLerp, 2) * p2.x;
result.y = Mathf.Pow(1 - timeLerp, 2) * p0.y + 2 * timeLerp * Mathf.Pow(1 - timeLerp, 1) * p1.y + Mathf.Pow(timeLerp, 2) * p2.y;
result.z = Mathf.Pow(1 - timeLerp, 2) * p0.z + 2 * timeLerp * Mathf.Pow(1 - timeLerp, 1) * p1.z + Mathf.Pow(timeLerp, 2) * p2.z;
resultList.Add(result);
time = time + Time.deltaTime;
}
}