一阶贝塞尔曲线
B(t)=(1-t)P0+tP1;
二阶贝塞尔曲线
B(t)=(1 - t) * (1 - t)* P0+2*t*(1 - t) * P1 + t * t * P2;
为了模拟敌人AI(弓箭兵),射箭的运动轨迹,已知发射点和着地点,画出运动轨迹。
代码如下:
public class BezierMover : MonoBehaviour {
public Vector3[] points;
public float speed = 1;
private float mn, mx=1;
void Update()
{
Move(true);
}
Vector3 Plot(float t)
{
Vector3 pos = Vector3.zero;
//(1-t)*(1-t)
pos= (1 - t) * (1 - t)* points[0]+2*t*(1 - t) * points[1] + t * t * points[2];
return pos;
}
// Update is called once per frame
void Move(bool progress)
{
if (mx - mn > 0.001f)
{
mn += 0.001f* speed;
}
Debug.Log("mn:"+ mn);
Vector3 p1 = Plot(mn);
Vector3 p2 = Plot(mn + 0.001f);
transform.position = p1;
transform.rotation = Quaternion.LookRotation(p2 - p1);
}
public void OnDrawGizmos()
{
if (points.Length >= 3)
{
float c = 0;
Vector3 pp, p;
pp = Plot(c);
Gizmos.color = Color.blue;
for (int pt = 0; pt < 1000; pt++)
{
c += 0.001f;
p = Plot(c);
Gizmos.DrawLine(pp, p);
pp = p;
}
}
}
}
这样就得到一条平滑的曲线
当然还有三四五阶曲线,参考