JavaScript
Article

An Introduction to Verlet.js

By Ashraff Hathibelagal

verlet-js is a light-weight physics engine, authored by Sub Protocol, which you can use in your web-based games. If you are into science and engineering, you can use it in your simulations as well. As the name suggests, verlet-js is based on an iterative technique called Verlet integration used to calculate the behavior of objects in its two-dimensional world.

In this tutorial, I am going to teach you everything you need to know how to use this physics engine effectively in your projects.

Setup

To start, download the latest version of verlet-js from GitHub and include it in your web page using a script tag:

<script src="verlet-1.0.0-min.js"><script>

As the 2D world of this physics engine is drawn on a canvas, you have to add one to your web page:

<canvas width="800" height="300" id="canvas"></canvas>

Initializing a 2D World

To initialize a 2D world—you can also call it a simulation—you have to call the verlet-js constructor, called VerletJS(). To this constructor, you pass the dimensions of the canvas, along with a reference to the canvas itself:

var world;

function initializeWorld() {
   world = new VerletJS(800, 300, document.getElementById("canvas"));
}

Rendering the World

To draw the 2D world, you have to repeatedly call the frame() function, which performs all the physics calculations, and the draw() function, which draws all the particles and constraints that belong to the 2D world. How often you call these functions every second determines your world’s frame rate:

// The frame rate of the world
var fps = 32;

function renderWorld() {
   world.frame(16);
   world.draw();
   setTimeout(renderWorld, 1000 / fps);			
}

Activating the World

Now that you have functions to initialize and render the world, let’s add the code that calls them both when the page loads:

window.addEventListener("load", function() {
   initializeWorld();
   renderWorld();
});

At this point, if you try to run these snippets together in your browser, you won’t see anything happening in the canvas element because there is nothing in your world.

Adding Items to the World

The worlds you create with verlet-js can contain only particles. However, you can create constraints between particles to limit how they move relatively to each other. For instance, using a distance constraint, you can force two particles to always maintain a fixed distance between themselves. Similarly, using an angle constraint, you can force three particles to always maintain a fixed angle.

With a little bit of creativity, you can use particles and constraints to create complex shapes and behaviors.

Shapes

verlet-js has a helper function called tire() that allows you to quickly create simple shapes (composed of particles and constraints) without having to define the particles or constraints yourself. To create a triangle, you could add the following code to the initializeWorld function:

world.tire(new Vec2(100,100), 100, 3, 1, 1);

The first parameter specifies the co-ordinates of the origin of the shape, while the second parameter specifies the radius (the distance from the origin to all other points of the shape). The third parameter is the number of segments that make up the shape. The last two parameters specify the stiffness of the constraints.

With this statement in place, you obtain the following result:

See the Pen GJvXwV by SitePoint (@SitePoint) on CodePen.

Here’s another example of use of tire() that shows you how to create a square:

world.tire(new Vec2(100,100), 100, 4, 1, 1);

And this is a live demo of the result you obtain:

See the Pen ZGJMVX by SitePoint (@SitePoint) on CodePen.

Remember that the third parameter you pass to tire() specifies the number of triangular segments that form the shape, not the number of sides the shape has.

Lines

To create line segments that consist of two particles, you can use the lineSegments() function. It accepts an array of Vec2 objects that contains the positions of the particles that form the line segment, and a number that specifies the stiffness of the distance constraint between the particles.

Here’s how you create a line segment whose endpoints are at (100,100) and (150,150):

world.lineSegments([new Vec2(100,100), new Vec2(150,150)], 1);

The previous statement gives you the following result:

See the Pen xGLamJ by SitePoint (@SitePoint) on CodePen.

Cloths

Another helper function provided by verlet-js is called cloth(). It lets you create a group of particles and constraints that behaves like a piece of cloth. The following code shows you how to use it:

world.cloth(new Vec2(100,100), 200, 200, 10, 3, 1);

This function accepts quite a few arguments. The following list describes all of them:

  • The first parameter specifies the co-ordinates of the origin
  • The second and the third parameters specify the width and height of the cloth.
  • The fourth parameter specifies the number of segments in each row and column of the cloth
  • The fifth parameter, if non-zero, specifies which particles should be pinned
  • The last parameter specifies the stiffness of the constraints between all particles

The result of running the previous statement is displayed below:

See the Pen PqKdVw by SitePoint (@SitePoint) on CodePen.

Creating Custom Shapes

More complex shapes—those that cannot be created using the helper functions—can be created using the Composite class. A Composite object has two arrays: one that contains particles, called particles, and one that contains constraints, called constraints. To add a particle or a constraint to a Composite object, you have to use the push() function of the appropriate array.

The following code shows you how to create a triangle using three particles and three distance constraints:

var triangle = new world.Composite();
triangle.particles.push(new Particle(new Vec2(100,100)));
triangle.particles.push(new Particle(new Vec2(100,200)));
triangle.particles.push(new Particle(new Vec2(200,100)));

triangle.constraints.push(
   new DistanceConstraint(triangle.particles[0], triangle.particles[1],2)
);

triangle.constraints.push(
   new DistanceConstraint(triangle.particles[0], triangle.particles[2],2)
);

triangle.constraints.push(new DistanceConstraint(
   triangle.particles[1], triangle.particles[2],2)
);

Once your shape is ready, add it to your world using the following code:

world.composites.push(triangle);

As you can see, the world object has an array called composites that is meant to hold all Composite objects. Below you can see the result you obtain with the snippets described in this section:

See the Pen WvEgPG by SitePoint (@SitePoint) on CodePen.

Using Pins

You already saw pins in action when you created the cloth. As its name suggests, a pin is used to, well, pin a particle to the canvas. This means that a particle that is pinned will not be affected by gravity and, as such, will not move unless you drag it.

For example, the following code pins one of the particles that compose the triangle you just created:

// pins the first particle
triangle.pin(0, new Vec2(100,100));

By pinning a particle, you obtain the effect shown in the following demo:

See the Pen MwvqLv by SitePoint (@SitePoint) on CodePen.

Changing the Gravity

By default, objects in your 2D world fall downwards. However, you can change this behavior by changing the value of gravity, a property of the world. For example, to change your world such that the gravity pulls both downwards, and to the right, you can add the following code to the initializeWorld function:

world.gravity = new Vec2(0.2, 0.2);

By doing so, you obtain this result:

See the Pen xGLaMJ by SitePoint (@SitePoint) on CodePen.

Conclusions

Thanks to this introductory article, now you know how to use verlet-js. As we said, it’s a light-weight physics library to create a bouncy and interactive 2D world that is made up of particles and constraints. To learn more about it, you can go through its code and examples on GitHub or read the guides provided by Sub Protocol.

What do you think about this library? Have you ever used it? What did you create? Let’s start a discussion.

  • http://loige.co/ Luciano Mammino

    Amazing library and great tutorial :) More of these please!
    It would be great a series about something like “building a game with verlet js”

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.