Skip to content

Instantly share code, notes, and snippets.

@fffej
Created July 29, 2009 20:02
Show Gist options
  • Save fffej/158363 to your computer and use it in GitHub Desktop.
Save fffej/158363 to your computer and use it in GitHub Desktop.
(defn separation
"Avoid crowding neighbours (short-range repulsion)"
[boid boids]
(reduce
(fn [[x y] b]
[(- x (- (:x b) (:x boid)))
(- y (- (:y b) (:y boid)))])
[0 0]
(filter
(fn [b] (< (distance [(:x boid) (:y boid)] [(:x b) (:y b)]) separation-distance))
boids)))
(defn alignment
"Steer towards average heading of neighbours"
[boid boids]
(let [boid-count (count boids)
[vx vy] (reduce (fn [[x y] b] [(+ x (:dx b)) (+ y (:dy b))]) [0 0] boids)
[avg-x avg-y] [(/ vx boid-count) (/ vy boid-count)]]
[(double (/ avg-x 8)) (double (/ avg-y 8))]))
(defn cohesion
"Steer towards average position of neighbours"
[boid boids]
(let [boid-count (count boids)
[sx sy] (reduce (fn [[x y] b]
[(+ x (:x b)) (+ y (:y b))])
[0 0]
boids)
[mx my] [(int (/ sx boid-count)) (int (/ sy boid-count))]]
[(int (/ (- mx (:x boid)) 100)) (int (/ (- my (:y boid)) 100))]))
(defn behave
"Get the boid behaviour given boids"
[boid boids]
(let [[v1x v1y] (cohesion boid boids)
[v2x v2y] (alignment boid boids)
[v3x v3y] (separation boid boids)]
(update-position
(alter-velocity boid [(/ (+ v1x v2x v3x) 3)
(/ (+ v2y v2y v3y) 3)]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment