且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

任意大小的凸多边形之间的碰撞检测算法

更新时间:2022-11-10 09:03:42

我做了一些类似于计算多边形相交的操作,即查找某个顶点是否位于给定的多边形内。

I did something similar to compute polygon intersections, namely finding if a vertex sits within a given polygon.

您的算法是可靠的,并且对于凹多边形不起作用。您选择的线表示形式在接近无穷大的坡度上也是有问题的。我选择将两个向量用于我的向量,一个向量用于线的方向,一个向量用于线的参考点。通过这些,我可以轻松地得出线的参数化方程,并以各种方式使用它来查找与其他形状的交点。

Your algorithm is sound, and indeed does not work for concave polys. The line representation you chose is also problematic at slopes approaching infinity. I chose to use a couple of vectors for mine, one for the line direction, and one for a reference point on the line. From these, I can easily derive a parameterized equation of the line, and use that in various ways to find intersections with other shapes.

P = S +  t * D

该线的任何一点P都可以通过其坐标t来刻画在直线上,根据上述关系,其中S是参考点,D是方向向量。

Any point P of the line can be caracterized by its coordinate t on the the line, given the above relation, where S is the reference point, and D the direction vector.

此表示法可让您轻松定义平面的哪些部分是正方向和负方向(即线的上方和下方),这要归功于方向方向。现在,可以将平面的任何区域定义为几条线的负或正子平面的交点。因此,可以稍微更改多边形内的点算法以使用该表示形式,并添加所有方向顺时针指向的约束,并测试该点是否在所有线段的负子平面中(因此,您不需要

This representation lets you easily define which parts of the plane is the positive and the negative one (ie. above and below the line), thanks to the direction orientation. Now, any region of the plane can be defined as an intersection of several lines' negative or positive subplanes. So your "point within polygon" algorithm could be slightly changed to use that representation, with the added constraint of all the direction pointing clockwise, and testing for the point being in the negative subplane of all the lines (so you don't need the centre of the polygon anymore).

计算我使用的直线的点的边的公式如下:

The formula to compute the side of a point wrt a line I used is the following:

(xs - xp) * yd - (ys - yp) * xd

当点P靠近S时,会出现坡度问题。

The slope issue appears here when point P is close to S.

可以使用边顶点计算该表示,但是为了具有正确的子平面,必须按相继的顺序将多边形中的顶点保持不变。

That representation can be computed using the edge vertices, but in order to have correct subplanes, you must keep your vertices in your polygon in condecutive orders.

对于凹面多边形,问题要复杂一些:简要地说,您必须测试一下该点位于两个连续的凸边之间。这可以通过检查边缘上的点在投影时的坐标并确保其位于 0 length(edge)(假设方向已标准化)。请注意,它归结为检查点是否属于多边形内的三角形。

For concave polygons, the problem is a bit more complicated: briefly, you have to test that the point is between two consecutive convex edges. This can be achieved by checking the coordinate of the point on the edge when projected on it, and ensuring it stands between 0 and length(edge) (assuming that the direction is normalized). Note that it boils down to check if the point belongs to a triangle within the polygon.