# Line-Circle Collision Detection

Well compared to the previous collisions it definitely involves more calculations.

First we need to take into account the linear and circle equations, respectively:

_{x})

^{2}+ (y – C

_{y})

^{2}= r

^{2}

Before we can replace the y value on the circle equation we first have to solve it by using this property:

^{2}= a

^{2}-2ab + b

^{2}

Which will lead to:

^{2}– 2xC

_{x}+ C

_{x}

^{2}+ y

^{2}– 2yC

_{y}+ C

_{y}

^{2}= r

^{2}

And after we replace the y value with the linear equation the result will be:

^{2}+ (mx)

^{2}– 2xC

_{x}+ 2mxb -2mxC

_{y}+ C

_{x}

^{2}+ C

_{y}

^{2}-2bC

_{y}+ b

^{2}= r

^{2}

But because this is a quadratic equation we can use this formula:

^{2}+ bx + c = 0

^{2}– 4ac)

2a

Which will result in:

^{2}+ 1)x

^{2}+ (2(-C

_{x}+ m(b – C

_{y})))x + (C

_{x}

^{2}+ C

_{y}

^{2}– 2bC

_{y}+ b

^{2}– r

^{2}) = 0

__-2(-C__

_{x}+ m(b – C_{y})) ± √((2(-C_{x}+ m(b – C_{y})))^{2}-4(m^{2}+ 1)(C_{x}^{2}+ C_{y}^{2}– 2bC_{y}+ b^{2}– r^{2}))2(m

^{2}+ 1)

Now we’re ready to find the coordinates of both intersection points. But what if there’s only one? Or no intersection at all?

There’s an interesting little section of the quadratic formula that allows us to predict if the line is colliding with the circle or not:

^{2}– 4ac

If the value you want to find the square root of is negative (which would lead to an irrational number) then the collision isn’t occurring. But if the value is 0 then the line is a tangent. And any other positive value means there’s 2 intersection points.

}

if (Δ == 0) {

// The line is tangent to the circle

}

if (Δ > 0) {

// The line intersects the circle

}

All these steps work perfectly with any type of line… except one. The vertical line!

This is because its slope is a mathematical impossibility.

So in order to determine its intersection points with the circle we need to find a different formula:

_{y}± √(r

^{2}– (k – C

_{x})

^{2})

As for determining if the collision is occurring or not, the process is pretty much the same. You just need to determine if the value inside the square root is negative or not.