# 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

1. 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’).
2. The next step is to rotate the vector ‘N’ 90 degrees to gets the lines normal and to make it unit vector.
3. 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.
Problems:
Depending how many frames you have the collision can be imperfect. The ball can go pass the line a little before it realizes that it has passed the line. One way of preventing this is to test many steps before increasing the balls distance. Another solution would be solve for a ‘time’ when you know the ball will collide with the ball.
Another problem is that this only works for a single line in your program. I solved this by determining the closest line to the ball . I will talk about that in the next post.

### 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:

Determine if a point/ball is above a line

Posted by in Other

Tags: ,

### Tags

Fabulou wholesale Petr Mrazek jersey is back. Best choice to get the wholesale Petr Mrazek jersey is suitable for all style of people.