Boids捕食者和障碍物行为



我正在使用pygame在python中进行boids模拟。基本行为有效,但我现在正在尝试添加避障和捕食者。到目前为止,我很难弄清楚如何实现这些行为。

首先,我试图让猎物逃跑,让捕食者攻击。为了做到这一点,我需要以某种方式找到最接近的boid。我该怎么做?

另外,为了避开障碍物

,有人可以解释一下我将如何让猎物避开但不主动逃离静态障碍物吗?

我的完整代码在这里(github)。我真的很感激关于我将如何完成这两件事的任何和所有解释。

谢谢!

编辑:

富卡斯向我展示了如何做到这一点,但现在我遇到了一个新问题。

对于捕食者和猎物的行为,我现在有这个:

    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

(此代码在所有其他规则之后最后应用)。

要找到最短的距离,您可以这样做

def attack(self, prey_list):
    d_list = []
    for prey in prey_list:
        distX = self.rect.x - prey.rect.x
        distY = self.rect.y - prey.rect.y
        d = distX*distX+distY*distY
        d_list.append(d)
    shortest_distance = min(d_list)

为了获得最短的距离和猎物,你可以做到

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
   print nearest_prey, shortest_distance

相关内容

  • 没有找到相关文章

最新更新