圆与线段相交

lac*_*cas 5 java math geometry line

在此输入图像描述

  • 我有一个线段(开始x1,y1,结束x2,y2(D = 5,可以说))和一个圆(半径R,中心x3,y3)

如何检查我的线段是否与圆相交?

eno*_*ram 5

作为初步检查,您可以使用叉积计算点和线之间的距离:

\n\n
(x1,y1) = p1, (x2,y2) = p2\n(cx, cy) = c = circle center\ndelta = p2 - p1 (the difference vector)\nunit = delta/norm(delta) (the unit vector along the line segment)\n(c-p1) x unit = (cx-x1) * unity - (cy-y1) * unitx = d (distance of the circle center to the line)\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意d有一个方向(符号)。

\n\n

如果d在[-R,R]范围之外,则线段不能与圆相交。

\n\n

如果您的线段移动量不大,您可以保存单位向量以供以后重复使用。

\n\n

如果圆确实与直线相交(而不是线段),它可能仍然不与线段相交。检查这三个条件:

\n\n
    \n
  • p1位于圆内;范数(p1-c) < R
  • \n
  • p2位于圆内;范数(p2-c) < R
  • \n
  • 从直线到圆心的最近点位于p1和之间p2
  • \n
\n\n

(unit . p1 < unit . c < unit . p2) or (unit . p2 < unit . c < unit . p1)其中.是向量点积。

\n\n

如果这些条件都不成立,那么它们就不会相交。

\n\n

您可能还需要知道它们相交的位置:

\n\n
perp = (-unity, unitx) (The perpendicular vector)\npclosest = perp * d + c (The point on the line closest to the circle center)\ndline = sqrt(R^2 - d^2) (The distance of the intersection points from pclosest)\ni{1,2} = \xc2\xb1dline * unit + pclosest\n
Run Code Online (Sandbox Code Playgroud)\n\n

显然,您需要单独检查是否i{1,2}位于p1和之间p2,就像我们在上面的第三个条件中所做的那样。

\n