Most of the time people want to know if a circle is colliding with a line or not (you can do that by finding the shortest distance and check if it's equal or less to the width of the radius). But what if you need to know exactly where the line is intersecting the circle?
First we need to take into account the equation of the line and the circle:
But before replacing the Y in the circle equation we're going to expand it, using this formula:
So:
And by replacing the Y we get this:
Instead of trying to make the equation equal to X, we can use the quadratic equation instead:
So the quadratic equation for our intersection will be:
From here we just need to replace the values with the ones in the quadratic equation to find the Xs and then use those values in the line equation to determine the Y coordinate of the intersection points.
But what if the line isn't intersecting the circle? Or if the intersection point is actually a tangent?
There's a simple way to check which of the 3 situations is occurring before calculating the coordinates of the points.
If we take into account this section of the quadratic equation:
First we need to take into account the equation of the line and the circle:
y = m x + b
(x - Cx)2 + (y - Cy)2 = r2
But before replacing the Y in the circle equation we're going to expand it, using this formula:
(a - b)2 = a2 - 2ab + b2
So:
(x - Cx)2 + (y - Cy)2 = r2 <=> x2 - 2xCx + Cx2 + y2 - 2yCy + Cy2 = r2
And by replacing the Y we get this:
x2 - 2xCx + Cx2 + (m x + b)2 - 2(m x + b) Cy + Cy2 = r2
x2 - 2xCx + Cx2 + (m x)2 + 2mxb + b2 - 2mxCy - 2bCy + Cy2 = r2
Instead of trying to make the equation equal to X, we can use the quadratic equation instead:
ax2 + bx + c = 0
x = -b ± √(b2 - 4ac)
2a
2a
So the quadratic equation for our intersection will be:
x2 + (m x)2 - 2xCx + 2mxb - 2mxCy + Cx2 + b2 - 2bCy + Cy2 - r2 = 0
(m2 + 1)x2 + (-2Cx +2mb - 2mCy)x + (Cx2 + b2 - 2bCy + Cy2 - r2) = 0
From here we just need to replace the values with the ones in the quadratic equation to find the Xs and then use those values in the line equation to determine the Y coordinate of the intersection points.
There's a simple way to check which of the 3 situations is occurring before calculating the coordinates of the points.
If we take into account this section of the quadratic equation:
Δ = b2 - 4ac
if ( Δ < 0 ) {
// The line isn't intersecting the circle
}
if ( Δ == 0 ) {
// The line is tangent to the circle
}
if ( Δ > 0 ) {
// The line intersects the circle
}
// The line isn't intersecting the circle
}
if ( Δ == 0 ) {
// The line is tangent to the circle
}
if ( Δ > 0 ) {
// The line intersects the circle
}