What are rigid bodies?
A rigid body is an idealized solid object that does not deform. It has mass, position, orientation, linear velocity, and angular velocity. The physics engine advances these properties each frame using Newton's laws, then resolves collisions so objects don't pass through each other.
The simulation loop
Every frame, the engine: (1) applies forces and torques, (2) integrates velocity and position, (3) detects collisions between shapes, (4) resolves collisions with impulses. This cycle repeats 60+ times per second for real-time interaction.
function physicsStep(bodies, dt) {
// 1. Apply forces (gravity, user forces)
for (const body of bodies) {
body.velocity.y += gravity * dt;
body.velocity.x += body.force.x / body.mass * dt;
}
// 2. Integrate position
for (const body of bodies) {
body.position.x += body.velocity.x * dt;
body.position.y += body.velocity.y * dt;
}
// 3. Detect & resolve collisions
const contacts = detectCollisions(bodies);
resolveCollisions(contacts);
}Collision detection
For simple shapes (spheres, boxes), collision detection checks whether shapes overlap. Sphere-sphere is a distance check; box-box uses the Separating Axis Theorem (SAT). For complex meshes, engines use bounding volume hierarchies (BVH) to avoid checking every triangle pair.
Impulse resolution
When two objects collide, an impulse is applied along the contact normal. The impulse magnitude depends on relative velocity, masses, and the coefficient of restitution (bounciness). A restitution of 1 means perfectly elastic (no energy loss); 0 means perfectly inelastic (objects stick together).
function resolveContact(a, b, normal, restitution) {
const relVel = dot(
sub(a.velocity, b.velocity),
normal
);
// Don't resolve if separating
if (relVel > 0) return;
const j = -(1 + restitution) * relVel
/ (1/a.mass + 1/b.mass);
a.velocity.x += (j / a.mass) * normal.x;
a.velocity.y += (j / a.mass) * normal.y;
b.velocity.x -= (j / b.mass) * normal.x;
b.velocity.y -= (j / b.mass) * normal.y;
}Friction and damping
Friction prevents objects from sliding indefinitely. It's applied tangent to the collision surface using a Coulomb friction model. Linear and angular damping simulate air resistance and prevent infinite spinning. In ThinkInsideTheBox, you can adjust friction, damping, mass, and restitution per-object.
What to experiment with
Try dropping objects from different heights to see how restitution affects bounce height. Stack cubes to test stability. Increase mass ratios to see heavy objects plowing through light ones. Turn off friction to create an ice-like surface.