Boids in python; calculating distance between two boids

青春壹個敷衍的年華 提交于 2019-12-23 03:14:00

问题


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:


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)


来源:https://stackoverflow.com/questions/15619307/boids-in-python-calculating-distance-between-two-boids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!