diff --git a/Scripts/Utils/MathFunctions.cs b/Scripts/Utils/MathFunctions.cs index 66ffb10d..373376b1 100644 --- a/Scripts/Utils/MathFunctions.cs +++ b/Scripts/Utils/MathFunctions.cs @@ -61,4 +61,39 @@ public static class MathFunctions return new Tuple(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(); + } } \ No newline at end of file