Ball Physics Sim

A 2D physics simulation where you throw balls with the mouse and watch them collide with realistic momentum.

Dozens of coloured balls bouncing and colliding in a window, shifting from blue to red as they speed up
Balls shift from blue to red as they speed up, which makes energy transfer easy to see.

Click and drag to throw a ball like a slingshot. Balls bounce off each other using impulse physics, and their mass comes from their size, so bigger balls hit harder and get pushed around less. Pressing S spawns 100 balls to stress test the engine, and G switches collision detection between brute force and a spatial grid while it runs.

Collisions. When two balls overlap, the sim finds the collision normal between their centres and pushes them apart (the heavier ball moves less). If they're moving towards each other, it applies an equal and opposite impulse scaled by their masses and a bounciness factor. This conserves momentum and works at any angle.

Spatial grid. Checking every pair of balls is O(n²): 300 balls means 44,850 checks every frame. The grid splits the screen into cells at least as wide as the largest ball, and each ball is only checked against its own cell and the 8 around it. No collisions are missed, and a live HUD shows the number of pair checks each frame.

100 balls
Brute force 60 FPS · grid 60 FPS
300 balls
Brute force 58 FPS · grid 60 FPS
600 balls
Brute force 20 FPS · grid 60 FPS

Measured on an Intel Core 7 150U with a 60 FPS target.

The first version only swapped x-velocities using the 1D elastic collision formula, which broke as soon as balls hit vertically or stacked. Rewriting it as 2D vector impulses along the collision normal fixed it at any angle.

Input was also silently dropping, because pygame.event.get() was being called twice per frame and the second call got an empty queue.

  • Turning a 1D collision formula into 2D vector-based impulse physics.
  • Why position correction and velocity response need to be handled separately.
  • Measuring an O(n²) bottleneck and fixing it with spatial partitioning.