Added functions for calculating distance between poinst and lines

This commit is contained in:
MaddoScientisto 2025-08-23 16:17:26 +02:00
commit 1bc519d913

View file

@ -61,4 +61,39 @@ public static class MathFunctions
return new Tuple<float, float>(output, currentVelocity);
}
// --- Helpers ---
private static float Cross(Vector2 a, Vector2 b) => a.X * b.Y - a.Y * b.X;
// --- Point → infinite line ---
public static float DistancePointToLine(Vector2 p, Vector2 a, Vector2 b)
{
Vector2 ab = b - a;
float len = ab.Length();
if (len == 0f)
throw new ArgumentException("Line points must not be identical.", nameof(b));
// |(b - a) x (p - a)| / |b - a|
return Mathf.Abs(Cross(ab, p - a)) / len;
}
// --- Point → line segment ---
public static float DistancePointToSegment(Vector2 p, Vector2 a, Vector2 b)
{
Vector2 ab = b - a;
float abLenSq = ab.LengthSquared();
// Degenerate segment → distance to the single endpoint
if (abLenSq == 0f)
return (p - a).Length();
// Project p onto the line, normalize to [0,1], then clamp to segment
float t = (p - a).Dot(ab) / abLenSq;
t = Mathf.Clamp(t, 0f, 1f);
Vector2 closest = a + t * ab;
// Replacement for Vector2.Distance: length of the difference vector
return (p - closest).Length();
}
}