簡體   English   中英

python中的Boids; 計算兩個投標之間的距離

[英]Boids in python; calculating distance between two boids

我正在嘗試使用Python中的Boid對飛行中的鳥類的行為進行編程。 我還沒有發現太多,但是目前我被卡在定義兩個波德之間距離的函數上。 它必須使用公式(a,b)= sqrt((a_x-b_x)^ 2 +(a_y-b_y)^ 2))來計算,其中a和b是我必須計算距離的兩個向量, a_x和b_x是向量的x分量,而a_y和b_y是向量的y分量。 我在公式中收到有關索引的錯誤。 我嘗試了多種解決方法,但我不知道該怎么做...

這是我到目前為止所得到的。 我對編程很陌生,所以我只知道一些基礎知識,而且我不確定其余的內容是否還可以。

WIDTH = 1000            # WIDTH OF SCREEN IN PIXELS
HEIGHT = 500            # HEIGHT OF SCREEN IN PIXELS
BOIDS = 20              # NUMBER OF BOIDS IN SIMULATION
SPEED_LIMIT = 500       # FOR BOID VELOCITY
BOID_EYESIGHT = 50      # HOW FAR A BOID CAN LOOK
WALL = 50               # FROM SIDE IN PIXELS
WALL_FORCE = 100        # ACCELERATION PER MOVE


from math import sqrt
import random
X = 0
Y = 1
VX = 2
VY = 3

def calculate_distance(a,b):
    a = []
    b = []
    for x in range (len(a)):
        for y in range (len(b)):
            distance = sqrt((a[X] - b[X])**2 + (a[Y] - b[Y])**2)
            return distance


boids = []

for i in range(BOIDS):
    b_pos_x = random.uniform(0,WIDTH)
    b_pos_y = random.uniform(0,HEIGHT)
    b_vel_x = random.uniform(-100,100)
    b_vel_y = random.uniform(-100,100)
    b = [b_pos_x, b_pos_y, b_vel_x, b_vel_y]

    boids.append(b)

    for element_1 in range(len(boids)):
        for element_2 in range(len(boids)):
            distance = calculate_distance(element_1,element_2)

問題是:

  • 您沒有將任何boid數據傳遞到函數中,僅傳遞了索引element_1element_2 因此, calculate_distance對博伊德一無所知。
  • 即使您傳入boid數據,您也將為ab分配空列表,這意味着永遠不會執行循環的內部。

您想要類似的東西:

for element_1 in range(len(boids)):
    for element_2 in range(len(boids)):
        distance = calculate_distance(boids[element_1],boids[element_2])

接着

def calculate_distance(a,b):
    return sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)

暫無
暫無

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

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