Shiffman, Chapter 5

Physics Libraries

Box2D, toxiclibs, rigid bodies, joints, and springs — letting a library handle the hard physics so you can focus on creativity.

Prerequisites: Chapters 1-4. You need to understand vectors, forces, and particles first.
10
Chapters
2
Simulations
10
Quizzes

Chapter 0: Why Libraries?

In Chapters 1-4, we built physics from scratch: vectors, forces, particles. That was essential for understanding. But there are things we didn't handle: collisions between objects, rigid body rotation, constraints, joints, friction between surfaces.

These problems are hard. Collision detection alone is a deep field of computer science. Rather than implement it all ourselves, we can use a physics library — a tested, optimized engine that handles the math for us.

Why learn from scratch first? Three reasons: (1) Without understanding vectors and forces, the library's documentation would be incomprehensible. (2) Libraries have overhead — they're not always simpler to use. (3) For creative projects, you often want physics that are inspired by reality, not chained to it. Knowing the fundamentals lets you pick and choose.
Our hand-rolled physicsPhysics library
Simple forces (gravity, wind)Full rigid-body dynamics
No collision detectionAutomatic collision detection and response
No constraintsJoints, springs, motors, pulleys
Full creative controlMust work within the library's rules
Easy to understandMore complex API
What is the main advantage of a physics library over hand-rolled physics?

Chapter 1: Box2D Concepts

Box2D is a 2D rigid-body physics engine originally written in C++ by Erin Catto. It's been used in thousands of games (Angry Birds, Limbo, etc.) and ported to virtually every language.

Box2D's key concepts:

ConceptWhat it is
WorldThe container for all physics simulation. Handles gravity and time-stepping.
BodyAn object in the world. Has position, angle, velocity. Three types: static, dynamic, kinematic.
ShapeThe geometry attached to a body: circle, polygon, edge.
FixtureConnects a shape to a body with physical properties: density, friction, restitution (bounciness).
JointA constraint connecting two bodies: revolute, distance, prismatic, pulley, gear.
The separation of body and shape: In Box2D, a body is an abstract physical entity (position, mass, velocity). The shape defines its geometry. The fixture binds them together with material properties. This separation lets you change a body's shape or attach multiple shapes to one body.
In Box2D, what connects a shape to a body?

Chapter 2: The World

Everything in Box2D lives inside a World object. You create the world, set gravity, and then step it forward in time each frame.

pseudocode
world = new World(gravity: (0, 10))

each frame:
  world.step(timeStep, velocityIterations, positionIterations)
  # world updates all bodies automatically
  # we just query their positions and draw
The critical mental shift: With our hand-rolled physics, we computed the motion. With Box2D, the world computes everything. We just (1) set up bodies, (2) tell the world to step, and (3) read back positions and angles for drawing. We're no longer the physics engine — we're the graphics layer.

Box2D uses its own coordinate system (meters, not pixels) and its own unit scale. You'll need conversion functions to translate between Box2D's world and your screen pixels. A typical scale factor is 10 pixels per meter.

What is the programmer's job when using Box2D?

Chapter 3: Bodies & Shapes

Bodies come in three types:

TypeBehaviorExample
DynamicResponds to forces and collisions. Moves freely.A falling ball, a thrown box
StaticNever moves. Infinite mass. Other bodies collide with it.Ground, walls, platforms
KinematicMoves at a set velocity but isn't affected by forces.A moving platform, a conveyor belt

Creating a dynamic body with a box shape:

pseudocode
# Define the body
bodyDef = new BodyDef()
bodyDef.type = DYNAMIC
bodyDef.position = (5, 2)  # in meters
body = world.createBody(bodyDef)

# Define the shape
shape = new PolygonShape()
shape.setAsBox(1, 1)  # half-width, half-height

# Attach via fixture
fixtureDef = new FixtureDef()
fixtureDef.shape = shape
fixtureDef.density = 1.0
fixtureDef.friction = 0.3
fixtureDef.restitution = 0.5  # bounciness
body.createFixture(fixtureDef)
Restitution controls bounciness: 0 = no bounce (clay), 1 = perfect bounce (super ball). Friction controls surface grip. Density determines mass (density × area = mass).
Which body type never moves but other objects can collide with it?

Chapter 4: Joints

Joints connect two bodies together with constraints. They're what make things interesting beyond simple collisions.

Joint TypeWhat it doesReal-world analogy
RevoluteRotation around a shared pointA door hinge, a pendulum pivot
DistanceKeeps two bodies at a fixed distanceA rigid rod connecting two balls
PrismaticAllows sliding along one axis onlyA piston, an elevator
PulleyConnects two bodies via a pulleyAn elevator counterweight
MouseAttaches a body to the mouse cursorDragging an object
Revolute joints are pendulums: Remember our pendulum from Chapter 3? In Box2D, you'd just create two bodies (pivot and bob), connect them with a revolute joint, and let the engine handle everything: angular acceleration, collision with other objects, energy conservation. What took us 30 lines of trig now takes 5 lines of joint setup.
Which joint type allows rotation around a shared point (like a door hinge)?

Chapter 5: Collision

One of the biggest reasons to use a physics library is collision detection and response. In our hand-rolled physics, we checked for edge collisions (walls and floor). But what about objects hitting each other?

Collision detection has two phases:

Broad Phase
Quickly rule out pairs that can't possibly be colliding (using bounding boxes)
Narrow Phase
For remaining pairs, compute exact contact points using shape geometry

Box2D handles both phases automatically. You can also register contact listeners to get callbacks when collisions happen, so you can trigger sounds, particles, damage, or score changes.

Collision response includes computing the impulse (sudden change in velocity) based on the collision normal, the relative velocity, and the restitution of both surfaces. This is the math that makes a rubber ball bounce and a bag of sand thud.
What are the two phases of collision detection?

Chapter 6: toxiclibs & Springs

Box2D is built for rigid bodies. But what about soft, stretchy things? toxiclibs (by Karsten Schmidt) takes a different approach: particle-spring systems.

Instead of rigid shapes, toxiclibs gives you:

ConceptWhat it is
VerletParticleA point with position (uses Verlet integration — no explicit velocity)
VerletSpringA spring connecting two particles with a rest length and stiffness
VerletPhysicsThe world that steps the simulation
Verlet integration: Unlike our Euler integration (velocity += acceleration; position += velocity), Verlet integration derives velocity from the difference between current and previous positions. This makes constraints (springs, distance limits) much easier to enforce. The tradeoff: less intuitive, but more stable for connected systems.

toxiclibs is ideal for cloth, soft bodies, hair, rope, and anything that stretches. You define a mesh of particles connected by springs, and the physics engine keeps them at their rest lengths (approximately).

What is the key difference between Box2D and toxiclibs?

Chapter 7: Soft Bodies

A soft body is built from particles connected by springs in a mesh pattern. Imagine a grid of particles where each one is connected to its neighbors. The springs try to maintain their rest lengths, but they can stretch and compress, creating a jelly-like object.

pseudocode
# Create a grid of particles
for row in 0..10:
  for col in 0..10:
    particle = new Particle(col * spacing, row * spacing)
    world.add(particle)

# Connect neighbors with springs
for each pair of adjacent particles:
  spring = new Spring(p1, p2, restLength, stiffness)
  world.add(spring)
Cloth simulation: A rectangular grid of particles connected by springs, with the top row pinned (locked in place). Gravity pulls the particles down, springs hold them together, and the result is a draping cloth that responds to forces. Add diagonal springs for shear resistance.

The beauty of particle-spring systems is their simplicity. Each spring just pulls its two particles toward the rest length. But hundreds of springs working together create complex, organic behavior — another example of emergence from simple rules.

How do you create a soft body?

Chapter 8: Stacking Simulation

Below is a simplified rigid-body stacking simulation. Boxes fall from above and stack on a platform, colliding with each other. This demonstrates the core idea: the library handles all collisions and responses; we just draw.

Rigid Body Stacking

Click/tap to spawn a new box. Boxes fall under gravity, collide with each other, and stack on the ground. Simple AABB collision detection is used.

Note: This is a simplified collision system (not a full physics engine). Real Box2D handles rotation, friction between surfaces, and stacking stability far better. But the principle is the same: set up objects, let the engine step, draw the results.
In a library-based physics simulation, what does the programmer do each frame?

Chapter 9: Summary

TopicKey Takeaway
Why librariesThey handle collisions, constraints, and rigid body dynamics
Box2DWorld → Bodies → Shapes → Fixtures. Step world, read positions.
Body typesDynamic (moves), static (fixed), kinematic (scripted)
JointsRevolute, distance, prismatic, pulley, mouse
CollisionBroad phase + narrow phase, handled automatically
toxiclibsParticle-spring systems for soft bodies, cloth, rope
Verlet integrationPosition-based (no explicit velocity), great for constraints
The lesson: Learning physics from scratch gives you understanding and creative freedom. Libraries give you power and realism. The best approach is both: understand the fundamentals, then reach for a library when you need collision detection, constraints, or performance.

What we covered:

• Box2D architecture (world, bodies, fixtures, joints)
• Dynamic, static, kinematic bodies
• Collision detection (broad + narrow phase)
• toxiclibs and Verlet integration
• Particle-spring systems
• Soft bodies and cloth

What comes next:

Chapter 6: Autonomous Agents. We move from inanimate objects to objects with desires. Steering behaviors let our shapes seek, flee, wander, and flock — the first step toward artificial life.

Which library would you choose for a cloth or rope simulation?