Given a line segment (AB) and point (C), find the furthest point between (AB) and (C) on the line segment with a max distance (D)

geometrytrigonometry

Given a point $C=(2, 6)$ and a line segment $A=(4, -2)$, $B=(6, 4)$ I need to calculate the furthest point (on the line segment) between $AB$ and $C$, with the maximum distance $D$ provided.

Graph: https://i.sstatic.net/eVZTz.jpg

Some examples:

  • Given a distance $D=5.831$, an expected result would be $(5, 1)$ on the line segment.
  • Given a distance $D=6.964$, an expected result would be $(4.5, -0.5)$ on the line segment.

Best Answer

Thanks to Vasya, I realised that it just requires a circle around point C and then a function to find where the line intersects. Here's the code (C#):

static Vector2 IntersectCircle(Vector2 position, float radius, Vector2 start, Vector2 end) {
    var ax = start.X;
    var ay = start.Y;
    var bx = end.X;
    var by = end.Y;
    var cx = position.X;
    var cy = position.Y;
    var dx = bx - ax;
    var dy = by - ay;

    var a = dx * dx + dy * dy;
    if (a <= 0.000001f)
        return end;

    var b = 2 * (dx * (ax - cx) + dy * (ay - cy));
    var c = (ax - cx) * (ax - cx) + (ay - cy) * (ay - cy) - radius * radius;

    var t = (float)((-b - Math.Sqrt(b * b - 4 * a * c)) / (2 * a));
    return new Vector2(ax + t * dx, ay + t * dy);
}