0

I'm trying to implement a method to check if a circle and a line intersect. I took most of this code (fixed based on the answer), and also modified the code a bit to use Point's instead of Vector2f's`.

This is currently what I have:

private bool CircleLineIntersect(int x, int y, int radius, Point linePoint1, Point linePoint2) { Point p1 = new Point(linePoint1.X,linePoint1.Y); Point p2 = new Point(linePoint2.X,linePoint2.Y); p1.X -= x; p1.Y -= y; p2.X -= x; p2.Y -= y; float dx = p2.X - p1.X; float dy = p2.Y - p1.Y; float dr = (float)Math.Sqrt((double)(dx * dx) + (double)(dy * dy)); float D = (p1.X * p2.Y) - (p2.X * p1.Y); float di = (radius * radius) * (dr * dr) - (D * D); if (di < 0) return false; else return true; } 

It looks consistent with this algorithm, so I'm not sure what the problem is.

If anyone could provide guidance it would be much appreciated.

EDIT:

It doesn't seem to be calculating correctly. For example with input x=1272, y=1809, radius=80, linePoint1={X=1272,Y=2332}, linePoint2={X=1272,Y=2544} there shouldn't be an intersection (y+radius is less than both y values of the line segment), but the function is returning true.

2
  • What IS your problem? In what way does this code not do what you want? Commented Sep 2, 2013 at 4:15
  • @Aron It doesn't seem to be calculating correctly. For example with input x=1272, y=1809, radius=80, linePoint1={X=1272,Y=2332}, linePoint2={X=1272,Y=2544} there shouldn't be an intersection (y+radius is less than both y values of the line segment), but the function is returning true. Commented Sep 2, 2013 at 4:27

1 Answer 1

1

Error exists in your test case. Not only does the it intersect, but your line goes through the center of the circle. The line is a vertical line (X =1272). Your circle is centred about (1272, 1809). ERGO it goes through the centre.

Perhaps you have a misunderstanding between the terms line and line-segment, within mathematics.

Sign up to request clarification or add additional context in comments.

2 Comments

I need the function to test for a line segment, not a line. Is there anything I can change to make it test the segment instead of the line? Perhaps testing if the point of intersection is within the line segment?
I added some code to test if the intersection point lies within the line segment and it seems to work correctly now (although I'm not sure how efficient it is).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.