This a port of Dan Shiffman’s Processing Flocking example ported to Clojure.
(defn separation [boid boids] (let [dsep 25.0 filtered (separation-map boid (distance-filter boids 0.0 dsep))] (if-let [sum (reduce sum filtered)] (vm/div sum (count filtered)) zero)))
versus:
PVector separate (ArrayList boids) { float desiredseparation = 25.0; PVector sum = new PVector(0,0,0); int count = 0; // For every boid in the system, check if it's too close for (int i = 0 ; i < boids.size(); i++) { Boid other = (Boid) boids.get(i); float d = loc.dist(other.loc); // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself) if ((d > 0) && (d < desiredseparation)) { // Calculate vector pointing away from neighbor PVector diff = loc.sub(loc,other.loc); diff.normalize(); diff.div(d); // Weight by distance sum.add(diff); count++; // Keep track of how many } } // Average -- divide by how many if (count > 0) { sum.div((float)count); } return sum; }