ThreeJS Physics Constraint breakdown

A brief exploration of the main techniques and ideas of a physics simulation demo

You better not give a physic simulation conflicting constraints. Constraints are rules and the physic simulation makes sure its rules are all followed. Even if that means disaster and destruction.

That was my first experience with constraints. Distaster and Destruction. So, in this demo, I went with a simpler approach, a line. And like any line, in the digital or real world, lines are just a series of dots close together.

My next move with constraints is to create some cloth simulations. If you have any projects of your own, or found in the wild, let me know and I'll share them in the next issue.


Invisible Physics Line

The physics line is made with invisible spheres. These spheres are simulated by themselves but not rendered. Each sphere has a constraint to the sphere above, and the sphere below, excluding the edges.

In the images for today, I'll show you the invisible spheres. But in the live version, they are hidden

const constraint = new CANNON.DistanceConstraint(
1 * 1.12
Demo with only the hidden physics line spheres visible
Demo with only the hidden physics line spheres visible

Free Form Sphere physics

For each invisible sphere, we create 50 mini-spheres to follow them. These spheres are the ones you see in the actual demo. However, they don't interact with the invisible spheres, they just follow their position.

The invisible and visible only interact with their kind by applying a collisionFilterMask in cannonjs. This allows the invisible physics to drive the movement but not fill space!

Demo with all type of spherse visible
Demo with all type of spherse visible

Simple Shading

The shading is a dot product of the sphere plus the index of the sphere to give each one of them a distinct color when used in the cosine palette function.

float offset = uIndex + dot(vNormal, vec3(0.,0.,1.)) * 0.2;
Spheres in black and white shading
Spheres in black and white shading

Physics Interaction

Demos like these are made to be played with. So, I calculate the angle from the mouse to the center of the screen. Then, position the first invisible sphere on one edge, and place the last invisible sphere at the opposite angle.

Then, because the small spheres follow the invisible ones, it creates fun organic movement.

Zoomed out demo
Zoomed out demo