Search code examples
geometrycollision-detectionintersection

find distance in line-circle intersection


A line intersects a circle with center in C (cx,cy) and radius r. The line is described by a position P (px, py) and a direction D (dx, dy). P lies inside the circle and the line is infinitely long. What's the distance d from P to the point of intersection?

float Intersect(Vector2d C, float r, Vector2d P, Vector2d D){

    ...

    return d;
}

Solution

  • You can expand parentheses and solve quadratic equation for unknown t:

    ((px - cx) + t * dx)^2 + ((py - cy) + t * dy)^2 = r^2
    

    If (dx,dy) vector is normalized (unit length), then value of t (positive root if your line is really ray starting inside a circle) is needed distance.

    Formula for intersection point (is not needed in current statement)

    ix = px + t * dx
    iy = py + t * dy