2014-01-17 54 views
1

我正在編寫一個python程序,其中一個圓圈從用戶繪製的線條反彈。有多個圈子從牆上彈開。對於每一個,都應計算從圓心和球的最短距離。我更喜歡這個代碼是非常有效的,因爲我目前的算法滯後於計算機。如果a點是起點,b點是終點,c點是中心點,r是半徑,我將如何計算球之間的最短距離?如果球的X座標超出AB段的x座標範圍,該算法也應該可以工作。蟒蛇(tkinter)中的一條直線和一個圓之間的碰撞檢測

請發表python代碼

任何幫助將不勝感激!

這是我到目前爲止有:

lineList是4個值用戶繪製線條,它包含起點和終點座標列表

中心是球的中心

global lineList, numobjects 
     if not(0 in lineList): 

      beginCoord = [lineList[0],lineList[1]] 

      endCoord = [lineList[2]-500,lineList[3]-500] 

      center = [xCoordinate[i],yCoordinate[i]+15] 

      distance1 = math.sqrt((lineList[1] - center[1])**2 + (lineList[0] - center[0])**2) 

      slope1 = math.tan((lineList[1] - lineList[3])/(lineList[0] - lineList[2])) 

      try: 
       slope2 = math.tan((center[1] - beginCoord[1])/(center[0]-beginCoord[0])) 

       angle1 = slope2 + slope1 

       circleDistance = distance1 * math.sin(angle1) 

      except: 

       #If the circle is directly above beginCoord 
       circleDistance = center[1] - lineList[1] 


      global numbounces 

      if circleDistance < 2 and circleDistance > -2: 

       print(circleDistance) 

       b = False 

       b2=False 

       if xCoordinate[i] < 0: 

        xCoordinate[i] += 1 

        speed1[i] *= -1 

        b=True 


       elif xCoordinate[i] > 0: 

        xCoordinate[i] -= 1 

        speed1[i] *= -1 

        b=True 


       if yCoordinate[i] < 0: 

        yCoordinate[i] += 1 

        speed2[i] *= -1 

        b2=True 


       elif yCoordinate[i] > 0: 

        yCoordinate[i] -= 1 

        speed2[i] *= -1 

        b2=True 


       if b and b2: 

       #Only delete the line if the ball reversed directions 

        numbounces += 1 

        #Add a ball after 5 bounces 

        if numbounces % 5 == 0 and numbounces != 0: 

         numobjects = 1 

         getData(numobjects) 
        canvas.delete("line") 

        lineList = [0,0,0,0] 

Diagram of circles

+0

「請張貼python代碼...」是的,請張貼一些代碼! – TypeIA

+0

你可以展示你的嘗試。此外,這看起來更像是一個數學問題,而不是編程問題。 – Christian

回答

1

說得對,我們並不是在講線路,而是在講段。

我建議以下思路:由於球在某個方向移動

,可能與東西趴在一個180°弧碰撞的唯一點 - 這是前進的一部分。在某些時候,當你檢查碰撞時,你必須檢查這些點是否與某件事相碰撞。你檢查的點越多,碰撞的精確度越好,但複雜性就越差。

檢查碰撞:檢查是否有任何點位於段的極值之間。你可以通過首先檢查座標來做到這一點(例如給出看你的畫線,意思是A.x < B.x and A.y> B.yif (A.x <= point.x <= B.x && A.y >= point.y >= B.y如果條件滿足,你檢查3點是否構成一條線。由於您已經有了座標AB,您可以推導出該線的方程並檢查point是否滿足該座標。

簡而言之:您檢查point是否滿足線的方程式,並位於由2個點定義的矩形內。

如何讓你不得不檢查點:假設2k+1是要檢查在一些時間點的數量,C是你的中心r半徑和V運動矢量。然後,方向矢量左側和右側的點數將相等,並且爲k(圓與運動矢量交點處的+1點)。然後90°/k是一個角度分割。既然你知道運動矢量,你可以計算它和水平線之間的角度(假設它是angle)。您繼續添加向左並從遞減的運動向量右移90°/k的值正好爲k次(讓我們將此值表示爲i),並計算point的位置point.x = C.x + sin(i) * rpoint.y = C.y + cos(i) * r

Sry,我不知道python。

0

從圓到線的最短距離是從中心到該線的最短距離,減去圓的半徑。如果從中心到該線的距離小於該半徑,則該線穿過該圓。

找到從一個點到一條線的距離記錄在許多地方,包括here

對不起,沒有發佈Python代碼,但它非常基礎。