python - 快速测试以查看 2D 线段是否与 python 中的三角形相交
问题描述
在二维平面中,我有一条线段(P0 和 P1)和一个三角形,由三个点(t0、t1 和 t2)定义。
我的目标是尽可能有效地(在计算时间方面)测试线是否与三角形的边缘之一接触、切穿或重叠。
一切都是二维的!我希望有人可以帮我用python写这个。
感谢大家的帮助!
解决方案
对我来说幸运的是,线段永远不会在三角形内开始和结束,它总是会相交。下面是我在 python 中的代码。它基于 Kevin 的想法,即您只需一次评估每个线段坐标并查看它们是否相交。如果是直线和三角形,则运行代码 3 次。有人有问题吗?(在python中实现):
#Check to see if two lines intersect
# return a 1 if they intersect
# return a 0 if the do not intersect
def line_intersection_test( p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x,p3_y):
s1_x = float(p1_x - p0_x)
s1_y = float(p1_y - p0_y)
s2_x = float(p3_x - p2_x)
s2_y = float(p3_y - p2_y)
outcome = 0
s = float (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y)
t = float ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y)
if (s >= 0 and s <= 1 and t >= 0 and t <= 1):
outcome = 1
return outcome
#basically feed line segment and the three lines that form the triangle separately to line_intersect_test to see if they intersect
def triangle_intersection_test(vecX1, vecY1, vecX2, vecY2, triX1, triY1, triX2, triY2,triX3, triY3):
side_1_test = line_intersection_test(vecX1, vecY1, vecX2, vecY2, triX1, triY1, triX2, triY2)
side_2_test = line_intersection_test(vecX1, vecY1, vecX2, vecY2, triX2, triY2, triX3, triY3)
side_3_test = line_intersection_test(vecX1, vecY1, vecX2, vecY2, triX1, triY1, triX3, triY3)
result = side_1_test + side_2_test + side_3_test
if result > 0:
outcome = "motion detected"
else:
outcome = "motion not detected"
return outcome
`
推荐阅读
- ios - Swift 错误:调用函数写入文本时,“类型‘()’不能符合‘视图’;只有结构/枚举/类类型可以符合协议”
- reactjs - 如何将resourceTimeline与react fullcalendar一起使用?
- window - NSIS - 自定义页面、自定义大小、自定义确定和取消按钮,带有自定义字段
- ios - ld:找不到 -lCocoaAsyncSocket 的库 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- c# - ASP.NET 页面的 DOCTYPE 问题
- java - 数组列表
如何按月/年计算出现次数 - android - 让视图成为背景的“窗口”
- python - 如何在主函数中捕获异常,而不是在导入的库中
- javascript - 如何在按钮单击时更改整个 div 内容
- command-line-interface - databricks cli:收到 b'Bad 请求错误