<分区>
- 我有一个线段(开始 x1,y1,结束 x2,y2(假设 D=5))和一个 圆(半径 R,圆心 x3,y3)
如何检查我的线段是否与我的圆相交?
<分区>
如何检查我的线段是否与我的圆相交?
最佳答案
作为初步检查,您可以使用叉积计算点和线之间的距离:
(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)
请注意 d
有方向(标志)。
如果d
超出范围[-R,R],则线段不能与圆相交。
如果您的线段移动不多,您可以保存单位 vector 供以后重用。
如果圆确实与直线相交(与线段相反),它可能仍然不与线段相交。检查这三个条件:
p1
位于圆圈内;范数(p1-c) < Rp2
位于圆圈内;范数(p2-c) < Rp1
之间和 p2
: (unit . p1 < unit . c < unit . p2) or (unit . p2 < unit . c < unit . p1)
其中 .
是 vector 点积。
如果这些条件都不成立,则它们不相交。
您可能还需要知道它们相交的位置:
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
你显然需要单独检查是否i{1,2}
介于p1
之间和 p2
,就像我们在上面的第三个条件中所做的那样。
关于java - 圆与线段相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052507/