【问题标题】:Boids in python; calculating distance between two boidspython中的Boid;计算两个物体之间的距离
【发布时间】:2013-03-25 15:58:39
【问题描述】:

我正在尝试使用 Python 中的 boid 对飞行中鸟类的行为进行编程。我还没有找到太多,但目前我被困在定义两个 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)

【问题讨论】:

  • 在 calculate_distance 中,您将 a 和 b 设置为一个空列表,然后使用 for 循环...您可能不希望这样。
  • 您已定义(大写)XY,但在您的 calculate_distance for 循环中,您正在创建未使用的 xy。也许您打算使用这些?
  • “公式中的索引出现错误” 错误是什么?当我运行上面的代码时,我没有收到任何错误。
  • 我建议您在运行某些东西后将其发布在 Code Review 上。我想你会发现它很有帮助
  • 为了扩展 Michael Keijers 的回答,既然你说你是新人,calculate_distance 的前两行正在清除你所有的输入数据。

标签: python vector distance boids


【解决方案1】:

问题是:

  • 您没有将任何 boid 数据传递到您的函数中,只是 索引element_1element_2。所以calculate_distance不知道 关于 boids 的任何事情。
  • 即使您传入 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2021-11-21
    • 2019-11-26
    • 2019-07-10
    • 2019-06-19
    • 2021-01-14
    相关资源
    最近更新 更多