计算交点的高效数学算法

编程入门 行业动态 更新时间:2024-10-12 22:29:18
本文介绍了计算交点的高效数学算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于我正在开发的游戏,我需要一种可以计算交集的算法.我已经解决了这个问题,但我做的方式真的很糟糕,我希望这里有人能有一个更优雅的解决方案.

For a game I am developing I need an algorithm that can calculate intersections. I have solved the problem, but the way I have done it is really nasty and I am hoping someone here might have a more elegant solution.

一对点代表它们之间绘制的线的端点.给定两对点,绘制的线是否相交,如果相交,在什么点?

A pair of points represent the end points of a line drawn between them. Given two pairs of points, do the drawn lines intersect, and if so, at what point?

例如调用 (A.x, A.y)-(B.x, B.y) 和 (C.x, C.y)-(D.x, D.y) 行

So for example call the lines (A.x, A.y)-(B.x, B.y) and (C.x, C.y)-(D.x, D.y)

谁能想到解决办法?任何语言的解决方案都可以.

Can anyone think of a solution? A solution in any language will do.

一个我应该更清楚的点,如果交点超出线段的长度,算法必须返回假.

A point I should have made clearer, the algorithm must return false if the point of intersection is beyond the lengths of the line segments.

推荐答案

这里的大部分答案似乎都遵循以下总体思路:

Most of the answers already here seem to follow the general idea that:

  • 找到通过给定点的两条直线的交点.
  • 确定交点是否属于两条线段.
  • 但是当交叉不经常发生时,更好的方法可能是颠倒这些步骤:

    But when intersection does not occur often, a better way probably is to reverse these steps:

  • 以y = ax + b(通过A、B的线)和y = cx + d(通过C、D的线)的形式表示直线
  • 看看C和D是否在y = ax+b的同一侧
  • 看看A和B是否在y = cx+d的同一侧
  • 如果以上的答案都是否,则存在一个交集.否则没有交集.
  • 找到交叉点(如果有).
  • express the straight lines in the form of y = ax + b (line passing A,B) and y = cx + d (line passing C,D)
  • see if C and D are on the same side of y = ax+b
  • see if A and B are on the same side of y = cx+d
  • if the answer to the above are both no, then there is an intersection. otherwise there is no intersection.
  • find the intersection if there is one.
  • 注意:要进行第 2 步,只需检查 (C.y - a(C.x) - b) 和 (D.y - a(D.x) - b) 是否具有相同的符号.步骤 3 类似.第 5 步只是两个方程的标准数学运算.

    Note: to do step 2, just check if (C.y - a(C.x) - b) and (D.y - a(D.x) - b) have the same sign. Step 3 is similar. Step 5 is just standard math from the two equations.

    此外,如果您需要将每条线段与 (n-1) 条其他线段进行比较,为所有线预先计算步骤 1 可以节省您的时间.

    Furthermore, if you need to compare each line segment with (n-1) other line segments, precomputing step 1 for all lines saves you time.

    更多推荐

    计算交点的高效数学算法

    本文发布于:2023-11-29 21:13:50,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1647647.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:高效   交点   算法   数学

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!