一阶贝塞尔曲线
使用两个点绘制线段
p3=p1+(p2-p1)*t
- p1:起点;
- p2:终点;
- t:0-1;
- p3:线段L12上的点
两个点和t的变化(0-1)可得到一条线段
二阶贝塞尔曲线
使用三个点绘制曲线
p12=p1+(p2-p1)*t
p23=p2+(p3-p2)*t
p123=p12+(p23-p12)*t
p12是线段L12上的点,
p23是线段L23上的点,
p123是线段L12 23上的点
控制p2的位置,可改变曲线的弯曲程度
示例
一阶贝塞尔,二阶贝塞尔
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);}
}
绘制曲线
using UnityEngine;
public class DrawCurve : MonoBehaviour
{public Transform point;//位置1public 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));}}
}
改变p2位置
using UnityEngine;
public class ChangePos : MonoBehaviour
{[SerializeField] float moveSpeed = 10;private void Update(){transform.position += transform.up * Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;}
}