Skip to content

Instantly share code, notes, and snippets.

@FreyaHolmer
Created August 21, 2019 02:18
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FreyaHolmer/a2b5833fdb8bf0048a389f9a555f9855 to your computer and use it in GitHub Desktop.
Save FreyaHolmer/a2b5833fdb8bf0048a389f9a555f9855 to your computer and use it in GitHub Desktop.
Béziér curve utility class for converting a t value to percentage of distance along the spline
using UnityEngine;
public class LengthTable {
public float[] distances;
int SmpCount => distances.Length;
float TotalLength => distances[SmpCount - 1];
public LengthTable( OrientedCubicBezier3D bezier, int precision = 16 ) {
distances = new float[precision];
Vector3 prevPoint = bezier.points[0];
distances[0] = 0f;
for( int i = 1; i < precision; i++ ) {
float t = i / (precision - 1f);
Vector3 currentPoint = bezier.GetPoint( t );
float delta = (prevPoint-currentPoint).magnitude;
distances[i] = distances[i - 1] + delta;
prevPoint = currentPoint;
}
}
public float TToPercentage( float t ) {
float iFloat = t * (SmpCount-1);
int idLower = Mathf.FloorToInt(iFloat);
int idUpper = Mathf.FloorToInt(iFloat + 1);
if( idUpper >= SmpCount ) idUpper = SmpCount - 1;
if( idLower < 0 ) idLower = 0;
return Mathf.Lerp( distances[idLower], distances[idUpper], iFloat - idLower ) / TotalLength;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment