How to detect a collision between a circle and a line.
I just now finished another computer graphic school project and want to share a few things. As you can tell there is a few bugs, but that is a different story. So far I am going to do this any many parts. I wanted to start off by talking about how to detect a collision between a circle/ball with a line. I will later talk about how to find the reflection, what to with many different lines and what else I can brew up.
Here is a visual of what I am talking about:
Steps to detect collision
- Create 2 vectors, one from a point on the end point of the line , to the center of the ball (call it ‘AB’). The other one is the vector from point A to point B on the line (call it ‘N’).
- The next step is to rotate the vector ‘N’ 90 degrees to gets the lines normal and to make it unit vector.
- Then take the dot product of the last vectors. This will give you the distance between the ball center and the line. So when the distance becomes less than the radius of the ball then it collided.
Here is a code snippet with dot product, rotation , and unit vector
boolean checkCollision(){
float distance;
float dotLine;
vec CB = new vec(wall[min(k,p)], ballPos);
vec N = new vec(wall[min(p,k)], wall[max(k,p)]);
N = U(R(N));
dotLine = dot(CB, N);
if( (ballSize) > (dotLine) ){
return true;}
return false;
}
float dot(vec U, vec V) { // dot product
return U.x*V.x+U.y*V.y;
};
vec U(vec V) { // make unit vector
float n = n(V);
if (n==0) return new vec(0, 0);
else return new vec(V.x/n, V.y/n);
};
vec R(vec V) { // rotate 90 degrees
return new vec(-V.y, V.x);
};
Other steps in this program:


