【发布时间】:2016-05-12 01:50:11
【问题描述】:
我正在使用 pygame 在 python 中进行 boids 模拟。基本行为有效,但我现在正在尝试添加避障和捕食者。到目前为止,我无法弄清楚如何实现这些行为。
首先,我试图让猎物逃走,让掠食者发起攻击。为了做到这一点,我需要以某种方式找到最近的 boid。我该怎么做?
另外,为了避障,有人可以解释一下我如何让猎物避开静态障碍物,但不主动逃离?
我的完整代码是here (github)。对于我将如何完成这两件事,我真的很感激任何和所有的解释。
谢谢!
编辑:
fucas 已经向我展示了如何做到这一点,但现在我遇到了一个新问题。
对于捕食者和猎物的行为,我现在有这个:
def attack(self, prey_list):
nearest_prey = None
shortest_distance = None
for prey in prey_list:
distX = self.rect.x - prey.rect.x
distY = self.rect.y - prey.rect.y
d = distX*distX+distY*distY
if not shortest_distance or d < shortest_distance:
shortest_distance = d
nearest_prey = prey
# do something with nearest_prey, shortest_distance
trajectory_x = self.rect.x - nearest_prey.rect.x
trajectory_y = self.rect.y - nearest_prey.rect.y
self.velocityX -= trajectory_x
self.velocityY -= trajectory_y
这是为了猎物:
def defend(self, predator_list):
nearest_predator = None
shortest_distance = None
for predator in predator_list:
distX = self.rect.x - predator.rect.x
distY = self.rect.y - predator.rect.y
d = distX*distX+distY*distY
if not shortest_distance or d < shortest_distance:
shortest_distance = d
nearest_predator = predator
# do something with nearest_prey, shortest_distance
trajectory_x = self.rect.x - nearest_predator.rect.x
trajectory_y = self.rect.y - nearest_predator.rect.y
self.velocityX += trajectory_x
self.velocityY += trajectory_y
(此代码在所有其他规则之后最后应用)。
【问题讨论】:
-
只是为了让我知道如何改进我未来的帖子,为什么要投反对票?
-
要找到最近的,您必须计算到每个猎物的距离。使用毕达哥拉斯
a^2 + b^2 = c^2,其中c是距离,a = x1-x2和b = y1-y2。顺便说一句,找到最近的你可以比较c^2而不是c -
有没有更高效的方法?另外,我将如何比较距离?
-
顺便说一句,我已经有一个函数设置来计算距离。我只需要知道如何快速比较所有这些。
-
Python 有
min(list_with_numbers)
标签: python python-2.7 pygame artificial-intelligence boids