A Quadtree is a way to organise spatial data to efficiently locate them.
- Let's put 100 dots in the screen randomly, call them boids.
- We want to know which one of such boids are 50 pixels from the mouse, call this target area.
A simple way of doing this is going boid by boid and check if their
Y coordinates are inside the target area. This is computationally intensive because we have to do one check per boid in the screen, even if they are far away from the target area.
Give we have more than 5 boids in the screen the total area is divided in four rectangles of equal size. The same process is repeated on each of the smaller rectangles, creating a tree of quadrants (see what I did there?) until each quadrant has 5 boids or less.
In this example the screen is filled with 100 boids and the algorithm is started.
Once we have the Quadtree structure we can quickly check which boids are inside a given area by walking the structure and ignoring all the branches that don't collide with the target area, effectively ignoring most of the boids in the screen.
In this demo the boids are also moving, that means the Quadtree is updated more or less 60 times per second with the new position of the boids.
A blue rectangle is drawn around the mouse, every boid found inside that area is painted red.
maxEntities: Divide a quadrant if it contains more than
maxDepth: Do not split a quadrant more than
entitiesCount: Number of boids to create. Default:
entitySize: Size of each boid in pixels. Default:
hoverSize: Width of the target area in pixels. Default:
maxSpeed: Limits how fast can boids move. Default:
The demo is configured with query parameters in the URL: