mirror of
https://gitlab.com/MaddoScientisto/cirnogodot.git
synced 2026-07-03 19:01:16 +00:00
Added functions for calculating distance between poinst and lines
This commit is contained in:
parent
f148e7cac7
commit
1bc519d913
1 changed files with 35 additions and 0 deletions
|
|
@ -61,4 +61,39 @@ public static class MathFunctions
|
||||||
|
|
||||||
return new Tuple<float, float>(output, currentVelocity);
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue