@thi.ng/boids
Version:
n-dimensional boids simulation with modular behavior system
27 lines (26 loc) • 760 B
JavaScript
import { __ensureFn } from "../internal/ensure.js";
const cohesion = (maxDist, weight = 1, pred = () => true) => {
const $maxDist = __ensureFn(maxDist);
const centroid = [];
return {
weight: __ensureFn(weight),
update: (boid) => {
const { add, mulN, setN } = boid.api;
const neighbors = boid.neighbors($maxDist(boid), boid.pos.curr);
setN(centroid, 0);
const num = neighbors.length;
let used = 0, i, n;
for (i = 0; i < num; i++) {
n = neighbors[i];
if (n !== boid && pred(boid, n)) {
add(centroid, centroid, n.pos.curr);
used++;
}
}
return used > 0 ? boid.steerTowards(mulN(centroid, centroid, 1 / used)) : centroid;
}
};
};
export {
cohesion
};