Building a Flock Simulation with Javascript
Hello there! 👋 In this article, we’ll be exploring how to build a type of flock sim. called Boid Simulation. The only tools we are going to be using is a code editor of your choice (I'm using Visual Studio Code for this demo), as well as the p5.js Javascript graphic library.
- Required skills: Basic Html and Javascript knowledge 👩💻🖥️
Tip #1: the p5.js web editor
If you don’t want to download an editor app or the p5.js library for javascript, you can simply use the p5.js web editor instead!
Tip #2: VsCode p5.js extension
If you’re using Visual Studio Code like me, then you might be interested in installing the “p5.vscode” extension by Sam Lavigne. Among other things, it adds a command that creates a p5.js project for you, which saves a lot of time downloading the library manually.
After installing the extension, simply press F1 or go to View → Command Pallete, and run the command “Create p5.js Project”. After selecting in which directory it should be created, the project should look something like this:
• Getting Started
If you followed either of the tips above, you can skip this section, otherwise, you will need to download the p5.js library manually. The quickest way to do so is to download it at the p5.js website, or via the link below. https://github.com/processing/p5.js/releases/download/v1.4.1/p5.min.js
(Either p5.js or p5.min.js will work just fine)
Once that is done, create a folder and place the downloaded library inside. Now you can create the following files:
- index.html → This will be the core Html file that will run the Javascript (in line 7 change the ‘src’ to the corresponding p5.js library downloaded)
- sketch.js → This will be the main code that will run the p5.js simulation
• Setting up our Boid class
We can now move on to creating our Boid Class. This will be created on a separate script, let’s call it Boid.js; this class represents one boid of our simulation, and will be later on copied over and over to populate our canvas therefore it must have all the attributes and behaviors a particle in the simulation should have.
Remember to import the new Boid.js script in the index.html! You can do this adding another
<script></script>
tag under line 10, and change the ‘src’ to the new script’s path.
Our Boid class should be created as such (but you can experiment with other attributes like mass i.e.):
Great! Now that we have implemented our Boid class, we can move on to their first fundamental methods: show()
, update()
and edges().
• The show() Method
The show()
method is the simplest of them all, it simply prints the points on the canvas, according to their position attribute. The code goes as follows:
This should represent a Boid as circle in the simulation, for simplicity. But you can experiment with other shapes and orientations as you wish
Now, let’s populate our simulation with some Boids and make them appear with our new show()
method, shall we? On our sketch.js script we have to do 4 things:
- Create an array at the beginning of the file which will store our particles,
- Set a max number of particles to be spawned,
- Populate our new array with Boids,
- Make them appear with
show()
!
Cool, now when we open index.html we should see our Boid appearing at random points each time we reload the page. Next up, the update()
method.
• The update() and edges() Method
Now, to make them move, we must create the Update() method, to… well… update the position each frame according to the velocity of the Boid. We can accomplish this by adding the velocity to the position vector, and the acceleration to the velocity vector. This makes the position move through the velocity vector, and the velocity change according to acceleration. This will end up looking like this neat method:
Now, we can add this to the sketch.js to update our Boid’s positions each frame before displaying them:
If everything went as planned, now our points will be moving all across the canvas. To prevent them going astray, we can use the edges()
method to loop them around the canvas when they get to any border.
And simply call it before updating the position on the sketch.js:
Phew, now we have a working physics simulation, great work! We can move on to our Boid/Flocking behavior.
• The Boid Behavior
The way our particles will behave in order to form flocks works based on three simple principles: separation, alignment, and cohesion.
- Separation has to do with how the particle avoid colliding with each other, by changing their direction according to incoming particles in a certain range
- Alignment is the principle that makes a particle align its velocity vector with nearby particles, to make them move in the same direction
- Lastly, cohesion acts on the particles to influence them to gather to the average position of the nearby particles
We will implement these three behaviors in three separate methods, and then join them together for our boid behavior implementation. You may notice that the methods are very much alike, so repeated blocks of code will not be commented on twice.
The separate()
method:
The align()
method:
The cohesion()
method:
Now to join it all together, let's create a flock()
method to use force vectors:
And finally, call out the flock()
method after updating the edges particles in our sketch.js!
There, now if we play our simulation, instead of particles remaining random, they form flocks!
You can now experiment with different parameters of the simulation to get different results, such as altering values of perception radius, giving unequal weights to the force vectors of the boid behavior; or even working on optimizing and styling!
Anyways, thank you for reading! If you want to take a further look on my personal take of the Boid Simulation, you can follow this link: thiagowaib.github.io/code-compendium/boid-sim