Skip to content

Commit 66d219b

Browse files
fix(boids): update cohesion(), use filter predicate
1 parent 8e61726 commit 66d219b

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

packages/boids/src/behaviors/cohesion.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,39 @@
11
// SPDX-License-Identifier: Apache-2.0
2-
import type { FnU2 } from "@thi.ng/api";
2+
import type { Predicate2 } from "@thi.ng/api";
33
import type { Vec } from "@thi.ng/vectors";
44
import type { IBoidBehavior, ScalarOrField } from "../api.js";
55
import type { Boid } from "../boid.js";
66
import { __ensureFn } from "../internal/ensure.js";
77

8+
/**
9+
* Cohesion behavior. Attempts to move boid towards centroid of neighboring
10+
* boids within `maxDist`. The behavior itself can be weighted via `weight`.
11+
* Neighbors can be filtered via optional `filter` predicate, which receives
12+
* current boid as first arg and current neighbor as second. By default all
13+
* neighbors are considered.
14+
*
15+
* @param maxDist
16+
* @param weight
17+
* @param pred
18+
*/
819
export const cohesion = (
920
maxDist: ScalarOrField,
1021
weight: ScalarOrField = 1,
11-
amp?: FnU2<Boid, number>
22+
pred: Predicate2<Boid> = () => true
1223
): IBoidBehavior => {
1324
const $maxDist = __ensureFn(maxDist);
1425
const centroid: Vec = [];
1526
return {
1627
weight: __ensureFn(weight),
1728
update: (boid) => {
18-
const { add, maddN, mulN, setN } = boid.api;
29+
const { add, mulN, setN } = boid.api;
1930
const neighbors = boid.neighbors($maxDist(boid), boid.pos.curr);
2031
const num = neighbors.length;
2132
setN(centroid, 0);
2233
for (let i = 0; i < num; i++) {
2334
const n = neighbors[i];
24-
if (n !== boid) {
25-
amp
26-
? maddN(centroid, n.pos.curr, amp(boid, n), centroid)
27-
: add(centroid, centroid, n.pos.curr);
28-
}
35+
if (n !== boid && pred(boid, n))
36+
add(centroid, centroid, n.pos.curr);
2937
}
3038
return num > 1
3139
? boid.steerTowards(mulN(centroid, centroid, 1 / (num - 1)))

0 commit comments

Comments
 (0)