In a recent blogpost I demonstrated how to build purely functional quadtrees in submilliseconds and this week I'll take it up a notch and show how to add multiple focal points and add some boid flocking logic.A demoBelow you should see 200 boids acting as individuals when apart and as flocks when closer together.How to flockTo build this simulation, assuming you've read how to build a functional quadtree, we need only 3 thingsA way to represent a BoidSome fast way to get it's closest neighborsFigure out how these neighbors interactSo let's start with a generous representation of a Boid. I say generous because I'm purposely including more data than needed. The cost is a bit more memory but it makes it easier to be purely functional down the road:(def boid-defaults {:max-speed 2.0 :max-force 0.4 :perception 30}) (defn initialize-boids [ width height ] (->> (for [idx (range num-boids)] (merge boid-defaults {:id idx :position [(rand-int width) (rand-int height)] :max-w width :max-h height :velocity [(- (u/rand-float 3) 1.5) (- (u/rand-float 3) 1.5)] :acceleration [0 0]})) (reset! boids)))If you're new to clojure, be aware that 'for' is a way of walking a list and returning a list. In this case we walk over (range num-boids), ie the number of 0..num-boids and for each of those we select a random starting point and a random velocity vector (direction) - And then we pipe that list into reset! which stores it in an atom.Now that we have our flock (list of boids) we simply need to walk the list, updating the position of each boid relative to its velocity vector - But before that, we need to make sure that the velocity vector is pointing in a direction which is similar to how a flock of birds would move.The simplest way to model this, to my knowledge at least, is this:Find the boids that are close enough to affect the one you're updatingMake a new acceleration vector, which aligns the current boid to the average direction of his friendsCreate some cohesion in the flock, by sl...
First seen: 2025-12-22 04:33
Last seen: 2025-12-22 19:35