# Flocking Autonomous Agents

[CG]jupoulton
61.2K views

## Optimization

Complex systems require computational power. Here are a few tricks to make your simulation run faster:

### Squared distance

When calculating the distance from A to B, instead of using the euclidean distance, use the squared euclidean distance. The square root operation is a relatively costly one and is ultimately useless when comparing distances.

Using the Victor library:

function withinRangeOf(boid) {
return function(other) {
return boid.position.distanceSq(other.position) <= BOID_RANGE * BOID_RANGE;
};
}


### Caching

For functions that calculate a result without changing the state of the system, you can keep a cache of the result in case it is needed again.

For example, boid A calculates its distance to boid B. Does boid B need to calculate its distance to boid A?

### Less instances

In my code, I instantiate a vector with new Victor() many times per step. Depending on the interpreter and/or compiler, this can slow down the program considerably. To avoid this, you could use the same instance to calculate every single temporary force of every boid.

Granted, the code would likely be harder to read.

### Bin-lattice spatial subdivision

This technique consists in dividing the screen into a number of cells. Each cell references all boids it contains. When a boid moves from one cell to the other, the cells must be updated.

Each boid need only consider the other boids in it's own cell, and possibly the surrounding cells, instead of the entire population.

## Machine learning

Once you've created an environment and some boids, why not let the boids evolve and figure out the best weights to give their rules on their own? They could, for instance use a Genetic Algorithm to create an individual perfectly suited to the given environment. Combined with Neural Networks, you could create an extremely interesting simulation!

## Playing around

Remember that all my code is available on Github, why not use it as a starting block for your own simulation of flocking autonomous agents?

In this playground, we did not address the issue of the borders of the screen. The boids wrap around when they leave the area but most of the code does not take this into account.

## Special thanks

A big thanks to Daniel Shiffman who inspired me to create a course on this subject.

❤❤❤

Open Source Your Knowledge: become a Contributor and help others learn.