The intersection of a circle segment and a line

enter image description here

  • I have a line segment (start x1, y1, end x2, y2 (D = 5 lets say)) and a circle (radius R, center x3, y3)

How to check that if my line segment crosses my circle?

+4
source share
4 answers

As a preliminary check, you can simply calculate the distance between a point and a line using a cross-product:

(x1,y1) = p1, (x2,y2) = p2 (cx, cy) = c = circle center delta = p2 - p1 (the difference vector) unit = delta/norm(delta) (the unit vector along the line segment) (c-p1) x unit = (cx-x1) * unity - (cy-y1) * unitx = d (distance of the circle center to the line) 

Note that d has a direction (sign).

if d is outside the range [-R, R], then the line segment cannot cross the circle.

If the segments of your line do not move so much, you can save a unit vector for later reuse.

If the circle really intersects with the line (as opposed to the line segment), it still cannot intersect with the line segment. Check out these three conditions:

  • p1 lies inside the circle; norm (p1-c) R
  • p2 lies inside the circle; norm (p2-s) R
  • the closest point from the line to the center of the circle is between p1 and p2 :

(unit . p1 < unit . c < unit . p2) or (unit . p2 < unit . c < unit . p1) where . is a vector point product.

If none of these conditions are met, they do not intersect.

You may also need to know where they intersect:

 perp = (-unity, unitx) (The perpendicular vector) pclosest = perp * d + c (The point on the line closest to the circle center) dline = sqrt(R^2 - d^2) (The distance of the intersection points from pclosest) i{1,2} = ±dline * unit + pclosest 

Obviously, you need to separately check whether i{1,2} between p1 and p2 , as in the third condition above.

+4
source

If you have Line2D for your line segment and Point2D for the center of the circle, then just check <<22>.

+2
source

You have two implicit equations: (x-x0) ^ 2 + (y-y0) ^ 2-r ^ 2 = 0 for the circle, and v2 * x-v1 * y = v2 * x0-v1 * y0 for the line ( where v1 = x1-x2, v2 = y1-y2). Just solve the system of equations, than check if the solution is on your line segment (for example, check that the x and y coordinates of the solution are between the two coordinates of the point corresponding to the coordinates).

0
source

Derive (x, y) from (y2-y1)/(x2-x1)*x + D = y and (x-x3)^2 + (y-y3)^2 = R^2 . Then find out if (x, y) belongs to your line segment.

0
source

Source: https://habr.com/ru/post/1393600/


All Articles