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.

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
Comparing Docker and Podman: A Guide to Container Management Tools
Comparing Docker and Podman: A Guide to Container Management Tools
Vultr
How to Deploy Flask Applications on Vultr
How to Deploy Flask Applications on Vultr
Vultr
A Comprehensive Guide to Understanding TypeScript Record Type
A Comprehensive Guide to Understanding TypeScript Record Type
Emmanuel Onyeyaforo
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
SitePoint Sponsors
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
SitePoint Sponsors
Momento Migrates Object Cache as a Service to Ampere Altra
Momento Migrates Object Cache as a Service to Ampere Altra
Dave Neary
Dev Hackathon: Reusable Creativity on Wix Studio
Dev Hackathon: Reusable Creativity on Wix Studio
SitePoint Sponsors
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
SitePoint Sponsors
How to Build Lightning Fast Surveys with Next.js and SurveyJS
How to Build Lightning Fast Surveys with Next.js and SurveyJS
Gavin Henderson
45 Visual Studio Code Shortcuts for Boosting Your Productivity
45 Visual Studio Code Shortcuts for Boosting Your Productivity
Shahed Nasser
Google Cloud Is the New Way to the Cloud
Google Cloud Is the New Way to the Cloud
SitePoint Sponsors
Understanding Vultr Content Delivery Networks (CDNs)
Understanding Vultr Content Delivery Networks (CDNs)
Vultr
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form