簡體   English   中英

pygame,從點A獲得多邊形上的最近點

[英]pygame, get closest point on a polygon from point A

我有一個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

這段代碼改編自此處的一個答案,由於我無法確認任何一個答案因此我尚未將其標記為已解決我的問題。 我目前正在嘗試適應“ r(t)=(2,0)+ tP3P2”問題。 就目前而言,它無法正常工作。 我相信目前可能是我的代碼。

當我運行代碼並測試我的點(在兩點之間,並且該線應垂直於多邊形)時,繪制到了極限。

我的代碼打印出距離d3小於d2和d1,因此它返回P3作為最接近的點。 但是,它應該返回P2和P3之間的一個點。

紅線顯示它試圖到達的點。

在此處輸入圖片說明

我正在使用numpy來簡化線性代數的點和向量的處理。 在這里沒有必要重新發明輪子。

非常有趣的問題!

假設您有一個列表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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM