What is Ammo.js Collision Margin and Why It Matters

This article explains the concept of collision margins in ammo.js, a popular WebAssembly port of the Bullet physics engine. You will learn what a collision margin is, how it functions as a protective buffer around 3D objects, and why tuning this parameter is critical for maintaining high performance and visual stability in web-based physics simulations.

Understanding Collision Margins in Ammo.js

In ammo.js, a collision margin is a small, virtual “cushion” or boundary layer added to the outer shell of a collision shape. Instead of calculating collisions exactly at the mathematical boundary of a 3D mesh, the physics engine detects contact when another object penetrates this outer margin.

By default, ammo.js applies a collision margin (typically 0.04 units, or 4 centimeters if using the standard 1 unit = 1 meter scale) to most collision shapes. For some shapes, like spheres and capsules, this margin is embedded internally so the object does not appear bloated. For other shapes, like boxes, cylinders, and convex hulls, the margin expands outward from the defined dimensions.

Why Collision Margins are Critical for Performance

The collision margin is not just a rendering offset; it is a fundamental optimization tool for the physics solver. Here is why it is critical for performance:

1. Faster Collision Detection Algorithms

Ammo.js relies on the GJK (Gilbert-Johnson-Keerthi) algorithm to determine if two convex shapes are intersecting. Calculating exact polygon-on-polygon intersection is computationally expensive. The collision margin allows the algorithm to work with rounded, highly optimized mathematical representations of the shapes. This significantly reduces the CPU cycles required to detect collisions, which is vital for maintaining a smooth 60 FPS in single-threaded browser environments.

2. Prevention of “Tunneling” and Jitter

When fast-moving objects collide without a margin, they can pass completely through each other in a single physics step (known as tunneling) or penetrate too deeply. When the engine detects a deep penetration, it must apply massive corrective forces to push the objects apart. This leads to realistic-looking “jittering” or explosions of physics bodies. The collision margin acts as a shock absorber, giving the solver a buffer zone to gently resolve contacts before deep penetration occurs.

3. Reduced Solver Iterations

A physics engine resolves collisions iteratively. If objects penetrate deeply due to a lack of margins, the constraint solver has to run many more loops (iterations) to find a stable state. By keeping objects separated by a margin, the solver reaches a stable resolution much faster, dramatically reducing the overall performance overhead of the physics simulation.

Best Practices for Optimizing Margins

To get the best performance and visual quality in your ammo.js project, keep these practices in mind: