Skip to content

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

2D Physics Simulator

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.

Features

  • 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

How the physics works

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:

  1. Calculates the collision normal between their centers.
  2. Separates the balls along that normal, distributing the correction according to their masses.
  3. Calculates their relative velocity along the collision normal.
  4. Applies an impulse with a restitution value of 0.8 when the balls are moving toward each other.
  5. 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.

Interaction

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.

Controls

Input Action
Click & drag Launch a new ball
Right click Clear all balls
G Toggle gravity
Space Pause / unpause
R Reset to default balls

Build Instructions

Requirements

  • C++17 compiler (MinGW-w64 recommended on Windows)
  • SFML 2.6.1
  • CMake 3.16+

Steps

cmake -B build -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/PhysicsSim.exe

Tech

  • Language: C++17
  • Graphics: SFML 2.6.1
  • Build system: CMake

About

Interactive 2D rigid-body physics simulator in C++ using SFML with gravity, collisions, and impulse-based response.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages