Boids in python; calculating distance between two

2019-06-02 21:15发布

I'm trying to program the behaviour of birds in flight with boids in Python. I haven't found much yet but currently i'm stuck on the function defining the distance between two boids. It has to be calculated with the formula (a,b) = sqrt( (a_x - b_x)^2 + (a_y - b_y)^2) ) where a and b are the two vectors between which i have to calcualte the distance, a_x and b_x are the x-components of the vectors and a_y and b_y are the y-components. I get an error about the indices in the formula. I've tried solving in in a number of ways but i just can't figure out how to do it...

Here is what i've got so far. I'm very new to programming so I only know the basics and i'm not sure if the rest of what i've got is ok.;

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)

1条回答
相关推荐>>
2楼-- · 2019-06-02 21:45

The problems are:

  • You are not passing in any boid data into your function, just the indices element_1 and element_2. So calculate_distance does not know anything about the boids.
  • Even if you were passing in boid data you are assigning empty lists to a and b , which means the inside of your loop is never executed.

You want something like:

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

and then

def calculate_distance(a,b):
    return sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
查看更多
登录 后发表回答