java - 圆与线段相交

标签 java math line geometry

<分区>

enter image description here

  • 我有一个线段(开始 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) < R
  • p2位于圆圈内;范数(p2-c) < R
  • 从直线到圆心最近的点位于p1之间和 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/

相关文章:

svg - 如何沿着 SVG 线放置多个均匀分布的箭头?

java - 等待异步任务完成

java - 具有自定义布局的 AlertDialog 未显示

java - 如何通过 ksoap2 和 axis2 Web 服务正确使用 asynctask

java - 我该如何改进这个单例?

math - x86 中的进位/溢出和减法

javascript - 在javascript中计算值,其中0是-50,1是50

java - 如何使用 Java 计算器进行单操作数数学运算?

javascript - 如何通过从文件读取坐标自动画线?

android - 我如何在矩形 android 中画一条线