Last active
September 6, 2023 15:38
-
-
Save tntmeijs/6c5fdf4a165562eaa50a51c5709c1832 to your computer and use it in GitHub Desktop.
Bezier curves in Unity3D using Casteljau's algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
public class BezierCurve : MonoBehaviour | |
{ | |
// Casteljau's algorithm based on the implementation in: "3D Math Primer for Graphics and Game Development" | |
public static Vector3 Curve(List<Vector3> points, float t) | |
{ | |
Vector3[] allPoints = points.ToArray(); | |
int n = allPoints.Length; | |
if (n == 0) | |
{ | |
Debug.LogError("No positions specified!"); | |
return Vector3.zero; | |
} | |
else if (n < 3) | |
{ | |
Debug.LogError("Not enough positions for a Bezier curve!"); | |
return Vector3.zero; | |
} | |
while (n > 1) | |
{ | |
--n; | |
// Perform the next round of interpolation, reducing the degree of the curve by one | |
for (int i = 0; i < n; ++i) | |
{ | |
allPoints[i] = allPoints[i] * (1.0f - t) + allPoints[i + 1] * t; | |
} | |
} | |
return allPoints[0]; | |
} | |
// Example code to visualize the trajectory | |
// The "m_curvePoints" variable is a List<Vector3> that holds the curve's control points. | |
// | |
// private void OnDrawGizmos() | |
// { | |
// if (m_curvePoints == null) | |
// { | |
// return; | |
// } | |
// else if (m_curvePoints.Count == 0) | |
// { | |
// return; | |
// } | |
// | |
// const float delta = 0.01f; | |
// Vector3 previous = m_curvePoints[0]; | |
// | |
// for (float t = delta; t <= 1.0f; t += delta) | |
// { | |
// Vector3 point = BezierCurve.Curve(m_curvePoints, t); | |
// | |
// Gizmos.color = Color.magenta; | |
// Gizmos.DrawLine(previous, point); | |
// | |
// previous = point; | |
// } | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment