1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using UnityEngine;
- namespace Core.Utility
- {
- public class QuinticBezierCurve: MonoBehaviour
- {
- // 5个控制点
- public Vector3 p0; // 起点
- public Vector3 p1; // 控制点1
- public Vector3 p2; // 控制点2
- public Vector3 p3; // 控制点3
- public Vector3 p4; // 终点
- // 计算四阶贝塞尔曲线上的点
- // t: 参数,范围 [0, 1]
- public Vector3 CalculatePoint(float t)
- {
- // 确保 t 在 0-1 范围内
- t = Mathf.Clamp01(t);
- // 四阶贝塞尔曲线公式
- // B(t) = (1-t)^4 * P0 + 4(1-t)^3 * t * P1 + 6(1-t)^2 * t^2 * P2 + 4(1-t) * t^3 * P3 + t^4 * P4
- float u = 1 - t;
- float t2 = t * t;
- float t3 = t2 * t;
- float t4 = t3 * t;
- float u2 = u * u;
- float u3 = u2 * u;
- float u4 = u3 * u;
- Vector3 point = (u4 * p0) +
- (4 * u3 * t * p1) +
- (6 * u2 * t2 * p2) +
- (4 * u * t3 * p3) +
- (t4 * p4);
- return point;
- }
- // 示例:在场景中绘制曲线
- void OnDrawGizmos()
- {
- Gizmos.color = Color.yellow;
-
- // 绘制控制点
- Gizmos.DrawSphere(p0, 0.1f);
- Gizmos.DrawSphere(p1, 0.1f);
- Gizmos.DrawSphere(p2, 0.1f);
- Gizmos.DrawSphere(p3, 0.1f);
- Gizmos.DrawSphere(p4, 0.1f);
- // 绘制曲线
- Vector3 previousPoint = p0;
- int segments = 50;
-
- for (int i = 1; i <= segments; i++)
- {
- float t = i / (float)segments;
- Vector3 currentPoint = CalculatePoint(t);
- Gizmos.DrawLine(previousPoint, currentPoint);
- previousPoint = currentPoint;
- }
- }
- // 获取曲线的切线(导数)
- public Vector3 GetTangent(float t)
- {
- t = Mathf.Clamp01(t);
- float u = 1 - t;
-
- // 四阶贝塞尔曲线的导数
- Vector3 tangent = 4 * (u * u * u * (p1 - p0) +
- 3 * u * u * t * (p2 - p1) +
- 3 * u * t * t * (p3 - p2) +
- t * t * t * (p4 - p3));
-
- return tangent.normalized;
- }
- }
- }
|