Hi, I’m trying to use the Splines package and I was wondering if there are some built-in methods to get the nearest knot from a given world space position on a spline. I’ve found SplineUtility.GetNearestPoint but it returns a point in space.
After reading a bit the source code for the SplineUtility.GetNearestPoint, I decided for now to just iterate through all the knots in the spline to get the closest one.
I’m sharing the code just in case anyone needs it:
using UnityEngine.Splines;
using Unity.Mathematics;
public static class SplineExtensionMethods
{
public static bool TryGetNearestKnotIndex(this ISpline spline, float3 position, out int nearestIndex)
{
nearestIndex = -1;
if (spline == null || spline.Count == 0)
return false;
float minDistance = float.PositiveInfinity;
NativeSpline nativeSpline = new NativeSpline(spline);
for (int i = 0; i < spline.Count; i++)
{
float currentDistance = math.distance(nativeSpline[i].Position, position);
if (currentDistance < minDistance)
{
minDistance = currentDistance;
nearestIndex = i;
}
}
return true;
}
public static bool TryGetNearestKnotIndex(this ISplineContainer container, float3 position, out SplineKnotIndex nearestIndex)
{
nearestIndex = SplineKnotIndex.Invalid;
if (container == null || container.Splines.Count == 0)
return false;
float minDistance = float.PositiveInfinity;
for (int i = 0; i < container.Splines.Count; i++)
{
NativeSpline spline = new NativeSpline(container.Splines[i]);
for (int j = 0; j < spline.Count; j++)
{
float currentDistance = math.distance(spline[j].Position, position);
if (currentDistance < minDistance)
{
minDistance = currentDistance;
nearestIndex.Spline = i;
nearestIndex.Knot = j;
}
}
}
return true;
}
}