How to Use setCcdSweptSphereRadius in Ammo.js
This article explains the role of the
setCcdSweptSphereRadius method in ammo.js, the JavaScript
port of the Bullet physics engine. You will learn how this function
prevents fast-moving physics bodies from passing through solid
obstacles—a glitch known as “tunneling”—by defining an embedded bounding
sphere used during Continuous Collision Detection (CCD)
calculations.
Understanding the Problem: Tunneling
In default discrete physics simulations, object positions are calculated at specific time intervals (ticks). If an object is moving extremely fast, or if an obstacle is very thin, the object might be on one side of the obstacle in one frame and on the other side in the next frame. Because the engine only checks for collisions at these discrete steps, it misses the collision entirely. This is called tunneling.
To solve this, ammo.js uses Continuous Collision Detection (CCD). Instead of checking static snapshots, CCD tests the continuous path of the object over time.
The Role of setCcdSweptSphereRadius
Performing continuous collision checks on complex 3D meshes is computationally expensive. To keep simulations running smoothly in real-time, ammo.js simplifies the process by sweeping a basic sphere along the object’s movement path instead of its actual geometry.
The setCcdSweptSphereRadius method defines the radius of
this invisible swept sphere.
When CCD is active, the engine projects this sphere from the object’s previous position to its current position. If this swept sphere intersects with any collision geometry along the path, the engine triggers a collision response, successfully preventing the object from tunneling through walls or floors.
How to Implement it Correctly
For setCcdSweptSphereRadius to work, it must be paired
with setCcdMotionThreshold. You must set both values on
your rigid body:
// 1. Set the motion threshold
rigidBody.setCcdMotionThreshold(1.0);
// 2. Set the swept sphere radius
rigidBody.setCcdSweptSphereRadius(0.2);1. Motion Threshold
(setCcdMotionThreshold)
This value represents the velocity (in units per simulation step) above which CCD is triggered. If the object moves slower than this threshold, the engine uses standard, high-performance discrete collision detection. If it moves faster, it switches to CCD.
2. Swept Sphere
Radius (setCcdSweptSphereRadius)
This defines the size of the sweeping sphere.
- Size Guidelines: The radius of the swept sphere should generally be smaller than the physical object’s boundaries. A good rule of thumb is to set it to about 20% to 50% of the object’s smallest dimension.
- If the radius is too large: The object will trigger collisions before its actual visual mesh touches an obstacle, causing it to bounce or stop in mid-air.
- If the radius is too small (or zero): The swept sphere may pass through thin walls undetected, failing to prevent tunneling.