UNPKG

@thi.ng/boids

Version:

n-dimensional boids simulation with modular behavior system

23 lines (22 loc) 672 B
import { __ensureFn } from "../internal/ensure.js"; const cohesion = (maxDist, weight = 1) => { 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); const num = neighbors.length; setN(centroid, 0); for (let i = 0; i < num; i++) { const n = neighbors[i]; if (n !== boid) add(centroid, centroid, n.pos.curr); } return num > 1 ? boid.steerTowards(mulN(centroid, centroid, 1 / (num - 1))) : centroid; } }; }; export { cohesion };