definition
Bezier curve , also known as Bezier curve or Bezier curve , is a mathematical curve applied to two-dimensional graphics applications. General vector graphics software uses it to accurately draw curves. Bezier curves are composed of line segments and nodes . Nodes are draggable fulcrums, and line segments are like stretchable rubber bands.
The first is the first-order Bezier curve formula , as follows:
B(t)=P0+(P1−P0)t=(1−t)P0+tP1, t∈[0,1]
second order formula
B(t)=(1−t)2P0+2t(1−t)P1+t2P2, t∈[0,1]
third order formula
B(t)=(1−t)3P0+3t(1−t)2P1+3t2(1−t)P2+t3P3, t∈[0,1]
accomplish
There are many detailed tutorials on the Internet for deriving the details, here is only for application
First let's look at the second-order formula, B(t)=(1−t)2P0+2t(1−t)P1+t2P2, t∈[0,1]
What should we do if we want to draw a curve in unity?
Here we can try
First of all, the most basic thing is that we should obtain two coordinate points, which are the starting point coordinates and the end point coordinates. Secondly, we obtain the corresponding curve coordinates by adjusting the value of t
Corresponding to the second-order and third-order formula codes
public static class BezierTool
{
public static Vector3 GetBezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Mathf.Clamp(t, 0, 1);
float x1 = (1 - t) * (1 - t) * (1 - t);
float x2 = 3 * t * (1 - t) * (1 - t);
float x3 = 3 * t * t * (1 - t);
float x4 = t * t * t;
return p0 * x1 + p1 * x2 + p2 * x3 + p3 * x4;
}
/// <summary>
/// 起点,中间点,终点
/// </summary>
/// <param name="p0">起点</param>
/// <param name="p1">中间点</param>
/// <param name="p2">终点</param>
/// <param name="t"></param>
/// <returns></returns>
public static Vector3 GetBezier(Vector3 p0, Vector3 p1, Vector3 p2, float t)
{
float x1 = (1 - t) * (1 - t);
float x2 = 2 * t * (1 - t);
float x3 = t * t;
return p0 * x1 + p1 * x2 + p2 * x3;
}
}
test run code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BezierMove : MonoBehaviour
{
public Transform originPoint;
public Transform destinationPoint;
public Transform controlPoint;
float rate;
public float bezierNumber;
List<Vector3> path;
int index;
public float speed = 5;
public bool isStart = false;
private void Start()
{
path = new List<Vector3>();
for (var i = 1; i < bezierNumber; i++)
{
float temp = 1 / bezierNumber;
rate += temp;
rate = Mathf.Clamp(rate, 0, 1f);
Vector3 pathPoint = BezierTool.GetBezier(originPoint.position, controlPoint.position, destinationPoint.position, rate);
path.Add(pathPoint);
}
foreach (var item in path)
{
print(item);
}
index = 0;
}
private void Update()
{
if (!isStart)
{
return;
}
if (index < path.Count)
{
transform.position = Vector3.MoveTowards(transform.position, path[index], Time.deltaTime * speed);
if (Vector3.Distance(transform.position, path[index]) <= 0.1f)
{
index++;
}
}
}
}