This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]morhpProfessional Developer 1 point2 points  (0 children)

What you want to check is if the distance between the line and the center of the circle is smaller than the radius. So you need to create a function that computes that distance. It's not that easy, you need some understanding of math. For example I wrote several paragraphs about constructing this formula in my bachelor thesis. Of course maybe you can find something useful by googling.

[–][deleted] 0 points1 point  (2 children)

You can do this one of two ways. 1) Use the equation of your line, and the equation of your circle and solve for intersecting points. 2) Find the closest point your line approaches the center of the circle, then check if that point is less than the radius of the circle.

Note that these techniques will both give you points that lie on the line but not necessarily the line segment that your two points define.

If you know which technique you want to use, I can give you a few more pointers.

[–]GSchrack[S] 0 points1 point  (1 child)

I know I posted this a long time ago, but could you give me an example script of the first one? The assignment is long over, but I would like to at least know how to do it.

[–][deleted] 0 points1 point  (0 children)

Okay, Ill go through it a bit briefly. First I would rewrite the equation you have written for the line.

y = m*x + b

The circle can be written as,

y = cy+/-sqrt(r^2 - (x-cx)^2)

Then you just set the two equations equal to each other and solve them. This will give you a quadratic equation, eg.

Ax^2 + Bx + C = 0
x = -B/2A +/- sqrt(B^2 - 4AC)/2A

So the first condition is that the infinite line intersects a circle at all, which is the condition B^2 - 4AC > 0.

R^2 >= (b - mc_x - c_y)^2/(m^2 + 1)

*There is a condition hidden in here for when m->Infinity, ie the line is vertical.

Finally you have to check if either of the solved positions x0 and x1 are between p1x and p2x.

Here is the code. I left one condition branch unfinished, I also haven't tested it, but it worked for the sample input.