Boids predator and obstacle behavior
<p>I am working on a boids simulation in python with pygame. The basic behavior works, but I am now trying to add obstacle avoidance and a predator. So far, I am having trouble figuring out how to implement these behaviors.</p>

<p>First of all, I am trying to have the prey boids flee and the predators attack. In order to do that, I need to somehow find the closest boid. How would I do that?</p>

<p>Also, for obstacle avoidance, could someone please explain how I would make the prey avoid, but not actively flee from, a static obstacle?</p>

<p>My full code is <a href="https://github.com/FakeNameSE/pred-prey-boids" rel="nofollow">here</a> (github). I would really appreciate any and all explanations as to how I would accomplish these two things.</p>

<p>Thanks!</p>

<p>EDIT:</p>

<p>fucas has shown me how to accomplish that, but now I have a new problem. </p>

<p>For the predator and prey behavior I now have this:</p>

<pre><code>    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 &lt; 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
</code></pre>

<p>And this for the prey:</p>

<pre><code>    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 &lt; 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
</code></pre>

<p>(This code it applied last after all of the other rules).</p>