Understanding Matter.js Engine Velocity Iterations

In the Matter.js 2D physics library, the velocityIterations property of the Engine module determines how many times the physics solver computes and refines body velocities during each simulation step. This setting plays a critical role in determining the balance between physics accuracy and rendering performance. Understanding how velocityIterations works allows developers to fine-tune collision responses, eliminate simulation instability, and optimize game performance across different hardware.

Purpose of the Velocity Iterations Property

During each engine update, Matter.js executes an iterative solver to handle collisions, springs, and body constraints. Rather than solving complex physical interactions in a single pass, the engine solves them repeatedly to approach a realistic equilibrium.

The velocityIterations property specifically dictates the number of calculation passes the solver performs to resolve the velocities of interacting bodies. It determines how effectively forces, impulses, bouncing, friction, and constraint tensions are transferred through contacting or connected objects.

How Velocity Iterations Affect the Simulation

The default value for velocityIterations in Matter.js is 4. Adjusting this value leads to direct trade-offs:

Velocity Iterations vs. Position Iterations

Matter.js features two distinct solver configuration settings on the Engine: velocityIterations and positionIterations.

Both settings work in tandem. If objects bounce erratically or jointed mechanisms stretch unnaturally, increasing velocityIterations is typically the solution. If objects sink into each other or pass through walls, increasing positionIterations is the proper fix.

How to Configure Velocity Iterations

You can define velocityIterations when initializing your Matter.js engine or update it dynamically at runtime:

// Setting during engine creation
const engine = Matter.Engine.create({
    velocityIterations: 8,
    positionIterations: 6
});

// Adjusting at runtime
engine.velocityIterations = 6;

When to Adjust the Default Value

Keep the default setting of 4 for standard simulations. Consider increasing velocityIterations when developing games with fast-moving bodies, intricate ragdoll physics, or tall stacks of resting objects where stability is paramount. Consider decreasing the value when targeting mobile web browsers or running scenes with very high object counts where standard rigid-body precision is not critical.