Flocking Simulation with Boids Algorithm in JavaScript and p5.js

Added:

Topological Interaction and Sensory-Limitation Models

While Craig Reynolds' classic Boids algorithm relies on metric distance—where agents respond to all neighbors within a fixed physical radius—empirical biological research offers a significant counterpoint. Studies of real starling flocks (such as the StarFlag project) reveal that flocking animals interact based on topological distance rather than metric distance. Instead of tracking everyone within a spatial zone, individuals track a fixed number of nearest neighbors (typically six to seven), regardless of how close or far apart they are. Furthermore, classic Boids assumes agents possess omnidirectional awareness. Real-world alternative models incorporate visual occlusion, limited fields of view, and cognitive constraints. Switching from metric-based zones to topological, sight-limited interactions prevents artificial flock fragmentation during density changes and provides a much more biologically accurate representation of collective animal behavior.

Basic JavaScript programming, including Object-Oriented Programming (OOP) concepts such as classes, instances, and encapsulation.
Fundamentals of Euclidean vector mathematics, specifically vector addition, subtraction, normalization, and limiting magnitude, which are essential for computing physical forces.
Familiarity with the p5.js library, including its rendering loop (setup and draw functions) and basic 2D shape drawing methods.
Elementary physics concepts of kinematics, particularly how force accumulates into acceleration, which in turn updates velocity and position.
Spatial partitioning algorithms, such as Quadtrees or Bin Latices, to optimize the O(N^2) computational complexity of neighborhood searches in large-scale simulations.
Advanced steering behaviors established by Craig Reynolds, including path following, obstacle avoidance, wandering, and queueing.
Transitioning the simulation from 2D to 3D space using WebGL, Three.js, or Unity to model realistic flocking of birds or schooling of fish.
Integrating autonomous agent simulations with genetic algorithms or reinforcement learning to evolve adaptive flocking strategies under environmental pressures.
359.3K views6.9Klikes42:27@TheCodingTrainOriginal Release: 2018-12-11

A flocking simulation can be created using Craig Reynolds' Boids algorithm, which implements three simple rules—separation (steering to avoid crowding local flockmates), alignment (steering toward the average heading of local flockmates), and cohesion (steering to move toward the average position of local flockmates)—applied to individual agents (called Boids) that only perceive and respond to other agents within a certain radius, resulting in emergent flocking behavior from simple local interactions.