I needed to get the intersection between a line and a circle for a little design work I was doing with Processing. Finally it was easier than I thought thanks to PVector.

In this case one of the points of the line was also the center of the circle, so I guess that puts things a little easier, but it should work for other cases.

I tried looking for the “use the math” way and actually I found some posts at the Processing forum with more or less all the code, like this and this, and also a sketch on OpenProcessing that was so helpfull. But to be honest that was too much math and too many variables.

When I was going to dive into all that I found this other post that wasn’t exactly the case but almost, and pointed me to vectors as a solution. Then this example on “vector math” at the Processing site set things clear.

Working with vectors can be a little bit tricky at the begining but it’s worth it.

So, as I was using vectors each point was considered as one and this is what I did:

- Substract the center of the circle to the other point of the line. That way we get the direction.
- Normalize the result so we have it on a scale from 0 to 1.
- Multiply by the radius. At this point we have a vector with the direction of the line and the length of the radius.
- Add the center of the circle. Finally we have a point wich is situated at the distance of the radio from the center of the circle and in the direction of the line.

This would be the piece of code where all this is done:

`intersection = PVector.sub(linePoint, circleCenter);`

intersection.normalize();

intersection.mult(radio);

intersection.add(circleCenter);

And this is an example using it. The values are random so everytime it is executed they change, showing that it works whatever the values are:

float radio=100;
PVector linePoint;
PVector circleCenter;
PVector intersection;
void setup() {
size(640, 480);
noLoop();
}
void draw() {
linePoint = new PVector(random(width), random(height));
circleCenter = new PVector(random(width), random(height));
ellipse(circleCenter.x, circleCenter.y, radio*2, radio*2);
line(linePoint.x, linePoint.y, circleCenter.x, circleCenter.y);
intersection = PVector.sub(linePoint, circleCenter);
intersection.normalize();
intersection.mult(radio);
intersection.add(circleCenter);
noFill();
stroke(255, 0, 0);
ellipse(intersection.x, intersection.y, 14, 14);
}

### Like this:

Like Loading...

*Related*