pygame,从A点获取多边形上的最近点

时间:2017-11-01 18:27:40

标签: python pygame

我有一个带n个点的多边形,我想找到这个多边形上最接近我的玩家p的点。我该怎么做呢?

因此,为此,我迭代n个点的多边形中的每个点,如下所示:

for i in range(points.shape[0]-1):
    for j in range(i+1, points.shape[0):

这会迭代多边形中的每对点,我将其用作要比较的线段。

然后我检查极端点,并试图查看该线段上的点是否更近。这是我的代码:

def _get_closest_point(self, P1, P2, P3):
        if numpy.linalg.norm(P3) > numpy.linalg.norm(P2):
            tmp_p3 = P3
            P3 = P2
            P2 = tmp_p3

        Ax = P3[0] - P1[0]
        Ay = P3[1] - P1[1]

        Bx = P2[0] - P3[0]
        By = P2[1] - P3[1]

        t = (Ax*Bx + Ay*By)/(2*(math.pow(Bx, 2) + math.pow(By, 2)))

        f_prime_1 = 2*(math.pow(Bx, 2) + math.pow(By, 2))

        d3 = numpy.linalg.norm(P3 - P1)
        d2 = numpy.linalg.norm(P2 - P1)
        d1 = numpy.linalg.norm(P3 + t*(P2 - P3) - P1)

        print "d1 " + str(d1)
        print "d2 " + str(d2)
        print "d3 " + str(d3)

        if d2 < d3 and d2 < d1:
            return P2
        elif d3 < d2 and d3 < d1:
            return P3
        else:
            return P3 + t*(P2 - P3)

    def _get_closest_point_poly(self, points):
        p = None

        for x in range(points.shape[0]-1):
            for y in range(x+1, points.shape[0]):
                p1 = self.origin
                p2 = points[x]
                p3 = points[y]

                tmp_p = self._get_closest_point(p1, p2, p3)

                if not isinstance(p, list):
                    p = tmp_p
                elif numpy.linalg.norm(tmp_p) < numpy.linalg.norm(p):
                    p = tmp_p
        return p

此代码改编自一个答案here,我没有标记为解决我的问题,因为我无法确认任何一个工作。我目前正在尝试调整&#34; r(t)=(2,0)+ tP3P2&#34;题。现在看来它不起作用。我相信它可能是我目前的代码。

当我运行代码并测试我的点(位于两点之间且线应该与多边形垂直)时,绘制到极致。

我的代码打印出距离d3小于d2和d1,因此它返回P3作为最近点。但是,它应该返回P2和P3之间的一个点。

红线显示了它想要达到的目的。

enter image description here

我正在使用numpy来更容易地使用线性代数的点和向量。没有必要在这里重新发明轮子。

1 个答案:

答案 0 :(得分:3)

非常有趣的问题!

假设您有一个列表vertices并且有两个维度,以便存储每个顶点的x和y值。

只需遍历列表并在每个点上执行简单的距离公式并记录最低距离。

我希望这个答案有所帮助!如果您有任何其他问题,请在下面发布!

vertices = [[100, 100], [200, 200], [300, 300]]

player = [100, 200]

closestVertex = -1
shortestDist = -1

for vertex in vertices:
    x, y = vertex

    distance = (((x - player[0]) ** 2) + ((y - player[1]) ** 2))

    if(distance < shortestDist or shortestDist == -1):
        shortestDist = distance
        closestVertex = vertex


print(closestVertex)
相关问题