Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function separate(boids, boid) {
const [count, direction] = boids.reduce(
([count, direction], otherBoid) => {
const d = boid.position.dist(otherBoid.position);
if (d > 0 && d < CONFIG.desiredSeparation) {
// Calculate vector pointing away from neighbour
const diff = Vector.sub(boid.position, otherBoid.position)
.normalize()
.div(d); // Weight by distance
return [count + 1, direction.add(diff)];
}
return [count, direction];
},
[0, new Vector(0, 0)],
);
return count > 0
? direction
.div(count) // average
.normalize()
.mult(boid.maxSpeed)
.sub(boid.velocity)
.limit(boid.maxForce)
: direction;
}
function align(boids, boid) {
const [count, direction] = boids.reduce(
([count, direction], otherBoid) => {
const d = Vector.dist(boid.position, otherBoid.position);
return d > 0 && d < CONFIG.neighbourDist
? [count + 1, direction.add(otherBoid.velocity)]
: [count, direction];
},
[0, new Vector(0, 0)],
);
return count > 0
? direction
.div(count)
.normalize()
.mult(boid.maxSpeed)
.sub(boid.velocity)
.limit(boid.maxForce)
: direction;
}
function boidOf(x, y) {
return {
acceleration: new Vector(0, 0),
velocity: new Vector(Random.range(-1, 1), Random.range(-1, 1)),
position: new Vector(x, y),
r: Random.range(2, 4),
maxSpeed: 3,
maxForce: 0.05,
trail: [],
trailLength: Random.range(25, 60),
color: Random.pick(warm),
};
}
function boidOf(x, y) {
return {
acceleration: new Vector(0, 0),
velocity: new Vector(Random.range(-1, 1), Random.range(-1, 1)),
position: new Vector(x, y),
r: Random.range(2, 4),
maxSpeed: 3,
maxForce: 0.05,
trail: [],
trailLength: Random.range(25, 60),
color: Random.pick(warm),
};
}
function cohesion(boids, boid) {
const [count, direction] = boids.reduce(
([count, direction], otherBoid) => {
const d = Vector.dist(boid.position, otherBoid.position);
return d > 0 && d < CONFIG.neighbourDist
? [count + 1, direction.add(otherBoid.position)]
: [count, direction];
},
[0, new Vector(0, 0)],
);
if (count > 0) {
direction.div(count);
return seek(direction, boid);
} else {
return direction;
}
}
function boidOf(x, y) {
return {
acceleration: new Vector(0, 0),
velocity: new Vector(Random.range(-1, 1), Random.range(-1, 1)),
position: new Vector(x, y),
r: Random.range(2, 4),
maxSpeed: 3,
maxForce: 0.05,
trail: [],
trailLength: Random.range(25, 60),
color: Random.pick(warm),
};
}