An interactive 2D rigid-body physics simulation built from scratch in C++17 with SFML. The simulator models gravity, wall collisions, and multi-body collisions while letting users launch new objects into the scene with mouse input.
- Real-time motion using Euler integration
- Gravity with a 60 FPS simulation loop
- Pairwise circle collision detection
- Impulse-based collision response with restitution
- Mass-aware overlap correction and velocity updates
- Boundary collision response against all four window edges
- Click-and-drag launching with velocity based on drag distance and direction
- Randomized ball radius, mass, and color for newly launched objects
- Toggleable gravity, pause, reset, and clear controls
Each ball stores its position, velocity, radius, and mass. On every active frame, gravity is applied to vertical velocity, then position is advanced using the frame's elapsed time.
For ball-to-ball collisions, the simulator first checks whether the distance between two centers is smaller than the sum of their radii. When two balls overlap, it:
- Calculates the collision normal between their centers.
- Separates the balls along that normal, distributing the correction according to their masses.
- Calculates their relative velocity along the collision normal.
- Applies an impulse with a restitution value of
0.8when the balls are moving toward each other. - Updates both velocities based on their masses.
Wall collisions use the same restitution factor, reversing and damping the velocity component perpendicular to the wall. Newly created balls receive a mass derived from their radius, so differently sized objects respond differently during collisions.
Clicking and dragging creates a new ball at the starting point. The drag vector is reversed and scaled to produce its initial velocity, making the interaction behave like pulling back and launching an object.
| Input | Action |
|---|---|
| Click & drag | Launch a new ball |
| Right click | Clear all balls |
| G | Toggle gravity |
| Space | Pause / unpause |
| R | Reset to default balls |
- C++17 compiler (MinGW-w64 recommended on Windows)
- SFML 2.6.1
- CMake 3.16+
cmake -B build -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/PhysicsSim.exe- Language: C++17
- Graphics: SFML 2.6.1
- Build system: CMake