First order Bézier curve
Draw a line segment
p3=p1+(p2-p1)*t using two points
- p1: starting point;
- p2: end point;
- t:0-1;
- p3: The point on the line segment L12
Two points and the change of t (0-1) can get a line segment
second-order Bezier curve
Use three points to draw a curve
p12=p1+(p2-p1)*t
p23=p2+(p3-p2)*t
p123=p12+(p23-p12)*t
p12 is a point on line segment L12,
p23 is a point on line segment L23 point,
p123 is the point on the line segment L12 23.
Control the position of p2 to change the bending degree of the curve
example
First-order Bezier, second-order Bezier
using UnityEngine;
public static class Curve
{
public static Vector3 CurveOne(Vector3 begin, Vector3 end, float percentage)
{
return begin + (end - begin) * Mathf.Clamp01(percentage);
}
public static Vector3 CurveTwo(Vector3 begin, Vector3 center, Vector3 end, float percentage)
{
return CurveOne(CurveOne(begin, center, percentage), CurveOne(center, end, percentage), percentage);
}
}
draw a curve
using UnityEngine;
public class DrawCurve : MonoBehaviour
{
public Transform point;//位置1
public Transform point2;
public Transform point3;
[Range(1, 1000)]
public int length;//曲线平滑程度
float t;
public LineRenderer line;//显示曲线
private void Update()
{
if (line.positionCount != length + 1)
line.positionCount = length + 1;
for (int i = 0; i <= length; i++)
{
t = i;
line.SetPosition(i, Curve.CurveTwo(point.position, point2.position, point3.position, t / length));
}
}
}
change p2 position
using UnityEngine;
public class ChangePos : MonoBehaviour
{
[SerializeField] float moveSpeed = 10;
private void Update()
{
transform.position += transform.up * Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
}
}