p5.js tutorials — particle systems

Lilly Lin
2 min readApr 23, 2021

This page is a step-by-step walkthrough of a simple particle system written with p5.js! The finished sketch will look something like this:

[insert gif of sketch]

Concepts covered:

  • variables
  • functions
  • arrays
  • classes
  • objects

How it works: Each particle created in your particle system is an object, which will be generated and controlled by functions inside your class.

The class:

The basic syntax for declaring a class is starting with the class keyword, followed by the name of your class, and curly brackets. Inside will be your constructor. A constructor looks like a function, but it will always use the constructor keyword. You can use it to set attributes for your class object. In this example, we’re going to use it to set position, speed, color, and life span variables.

To create a new Particle object, use the new keyword:

For our example, the position, speed, and color are all determined randomly as the constructor is called. You could also set these by placing parameters in your constructor, like so:

Note: the this keyword is used to refer to your object’s internal variables.

Then creating a new Particle might look like this:

The next piece of the class is a function that will display the particle on the canvas. Let’s call this a draw function. (You can call it anything you want, unlike the constructor which must use the word constructor!)

You do not need to write the function keyword when writing functions inside your class. This draw function takes no parameters, when called it 1.) sets the color variable, 2.) sets the fill to that color, and 3.) draws a 20px circle at the x and y value determined by the constructor.

--

--