Taking a look under the hood of a physics engine

Anurag Hazra
May 16 · 5 min read

Have you ever wondered if you can make your own physics engine in JavaScript? If so, you have come to the right place. We are going to build a Physics engine from scratch in JavaScript.

Photo by Chad Kirchoff on Unsplash

Before we start, I should mention that this tutorial assumes you have a good understanding of Vectors.

Don’t worry if you do not yet have this understanding — Vectors are simple: get the Vector.js

What Is Verlet Physics?

According to Wikipedia:

Verlet integration is a numerical method used to integrate Newton’s equations of motion. It is frequently used to calculate trajectories of particles in molecular dynamics simulations and computer graphics. The algorithm was first used in 1791 by Delambre and has been rediscovered many times since then, most recently by Loup Verlet in the 1960s for use in molecular dynamics.

In simple terms, Verlet physics is just a system of connected dots.

In a Verlet system, we have 2 main components:

A Box. Connected With Dots And Sticks
  1. Points (dots)
  2. Constraints (sticks(

Dots

The dots have very simple physics applied to them.

We have to keep track of the dots’ current and old positions to add the physics behavior to them — you'll see this when we actually implement it.

Dot.js

We have the basic setup, now let's render the dots and make them move.

Dot.js - update()

The update function will update the position and handle the physics of the dot.

Basically, to do Verlet integration we have to calculate velocity based on dots old position.

In the first line, we are subtract the current position from the old position to get the desired velocity. After calculating the velocity, we apply friction to the dots so they come to rest instead of sliding forever.

Then, we update the old position by saying this.oldpos.setXY(this.pos.x, this.pos.y) and add the velocity and gravity to position.

We also want to make them stay inside the canvas so we have to add some checks. We will also add another function: constrain():

Dot.js - constrain()

Let’s add the render method too:

Dot.js - render()

Setting up:

index.js - setting up the example

We added a lot more dots in random positions and then update() constrain() render() them.

Let's see what that looks like:

Verlet Physics — Dot.js

Nice — it's just a start but finally we have something.

Now we are going to add the sticks!

Sticks

Sticks are the core of Verlet physics. Sticks make sure that the dots don’t get too far or too close to each other — they constrain dots to a certain distance.

https://slsdo.github.io/blob-family/#constraint

Stick.js class is fairly simple. It will take two Dots as an argument and a length. but if the length is not defined we will calculate the length based on the dot’s position.

Stick.js

Now let's add the actual core of the algorithm. This resolves and updates the dot’s position based on the stick’s distance, ultimately constraining it to a certain distance from all other dots.

Stick.js - update()

Okay, I think we are good to go! Let’s add the render function:

Stick.js - render()

Setting up:

Setting up - creating a box

Let’s see the results:

VerletPhysics - a simple Box

As you can see, we have a box! Well, a box that acts like it’s made of Jello, anyway. That’s because in a single frame, one update per stick is not enough to make the dots rest at their length. We have to iterate the simulation as many times as we can — the more the iterations, more the rigid box will be.

Adding these lines to the existing code will make the box rigid:

Okay, let's take a look at an updated example:

VerletPhysics — Updated Example

Looks amazing, doesn’t it?

Entity.js: managing dots and sticks in one place

Okay, now we have Dot.js and Stick.js. Both are working nicely but the problem is we don't have much control over how we use them.

We will create an Entity Class which will easily handle the Updates and Renders of the Verlet Object. I'm going to paste the whole code here — it’s nothing special:

Entity.js — Basic OOP

Using the Entity Class:

Yes, this is looking pretty clean and manageable!

Let's take a look at the final result:

Now we can create lots of fun Verlet Shapes with this Entity.js class!

Verly.js: A physics engine I wrote

Verly.js is a Robust Verlet physics engine I wrote. It has many cool features:

  1. Attraction — Repulsion behavior
  2. Basic Shapes
  3. Box, Hexagon, Cloth, Rope, Ragdoll
  4. Cloth Tearing
  5. Typography and Text

With Verly.js you can create a tearable cloth in just 15 lines of code:

Verly.js Tearable Cloth In 15 Lines Of Code

Demo: https://anuraghazra.github.io/Verly.js/

Source-code: https://github.com/anuraghazra/Verly.js

Examples: https://anuraghazra.github.io/Verly.js/examples

Take a look at some of the examples in my Verly.js Physics Engine which I created some time ago. I added almost everything in that engine.

Spherical Shapes anuraghazra.github.io
Attraction Repulsion Behavior anuraghazra.github.io
RagDoll anuraghazra.github.io
anuraghazra.github.io

Codepen examples:

Verly.js’s API is easy to use and flexible because of its Entity Component Structure.

Thanks for reading — I hope you learned something!


Other places to learn about Verlet physics:

  1. Keith Peter’s CodingMath Verlet Physics Videos.
  2. Amazing Article At DataGenetic http://datagenetics.com/blog/july22018/index.html

Better Programming

Advice for programmers.

Anurag Hazra

Written by

I am a javascript lover. Canvas Graphics, Web Interactivity, Web Physics Simulations all kind of fun stuff. #CreativeCoder

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade