An Introduction to Verlet.js

Share this article

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.

Key Takeaways

  • Verlet.js is a lightweight physics engine for JavaScript, primarily used for creating 2D physics simulations. It uses Verlet integration, a numerical method used to solve Newton’s equations of motion.
  • To use Verlet.js in a project, it must first be included in the HTML file. Once Verlet.js is included, its functions can be used to create physics simulations. The library provides a variety of functions for creating particles, constraints, and more.
  • Verlet.js offers several key features that make it a powerful tool for creating physics simulations. These include particle systems, constraints, and collision detection.
  • Verlet.js uses a method called “continuous collision detection” to handle collisions. This method involves checking for collisions at every step of the simulation, ensuring accurate detection even at high speeds or with small objects.
  • Verlet.js is primarily designed for 2D simulations, but it can be used for 3D simulations with a deeper understanding of the library and the principles of physics simulations. Manual handling of the third dimension is required, as the library’s built-in functions are designed for 2D.

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.

Frequently Asked Questions about Verlet.js

What is Verlet.js and how does it work?

Verlet.js is a lightweight physics engine for JavaScript, primarily used for creating 2D physics simulations. It uses Verlet integration, a numerical method used to solve Newton’s equations of motion. This method is particularly popular in computer graphics for simulating particles, cloth, ragdolls, and more. Verlet.js simplifies the process of creating these simulations by providing a set of tools and functions that handle the complex calculations involved in physics simulations.

How do I install and use Verlet.js in my project?

To use Verlet.js in your project, you first need to include it in your HTML file. You can do this by downloading the Verlet.js file and linking it in your HTML file using the script tag. Once you’ve included Verlet.js, you can start using its functions to create physics simulations. The library provides a variety of functions for creating particles, constraints, and more.

What are the key features of Verlet.js?

Verlet.js offers several key features that make it a powerful tool for creating physics simulations. These include particle systems, constraints, and collision detection. Particle systems allow you to create and manage groups of particles, while constraints let you define the relationships between particles. Collision detection, on the other hand, allows you to detect and respond to collisions between particles.

How does Verlet.js handle collision detection?

Verlet.js uses a method called “continuous collision detection” to handle collisions. This method involves checking for collisions at every step of the simulation, rather than only at discrete intervals. This ensures that collisions are detected accurately, even at high speeds or with small objects.

Can I use Verlet.js for 3D simulations?

While Verlet.js is primarily designed for 2D simulations, it is possible to use it for 3D simulations as well. However, this requires a deeper understanding of the library and the principles of physics simulations. You would need to manually handle the third dimension, as the library’s built-in functions are designed for 2D.

How can I optimize my Verlet.js simulations for performance?

There are several ways to optimize your Verlet.js simulations for performance. One way is to limit the number of particles and constraints in your simulation. Another way is to use the library’s built-in functions for collision detection and resolution, which are optimized for performance.

What are some common use cases for Verlet.js?

Verlet.js is commonly used in game development and computer graphics to create realistic physics simulations. This includes simulations of cloth, particles, ragdolls, and more. It can also be used in scientific simulations to model physical systems.

How does Verlet.js compare to other physics engines?

Verlet.js stands out for its simplicity and ease of use. While other physics engines may offer more features, Verlet.js focuses on providing a simple and intuitive interface for creating physics simulations. This makes it a great choice for beginners and those who value simplicity and ease of use.

Can I contribute to the development of Verlet.js?

Yes, Verlet.js is an open-source project, and contributions are welcome. If you’re interested in contributing, you can check out the project’s GitHub page for more information.

Where can I find more resources to learn about Verlet.js?

There are several resources available online to learn more about Verlet.js. The project’s GitHub page is a great place to start, as it includes a detailed readme and examples. There are also several tutorials and articles available online that cover the basics of using Verlet.js.

Ashraff HathibelagalAshraff Hathibelagal
View Author

Hathibelagal is an independent developer and blogger who loves tinkering with new frameworks, SDKs, and devices. Read his blog here.

AurelioDgamesjavascript librariesphysics engineVerletVerlet.js
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week