Skip to content
This repository was archived by the owner on Mar 7, 2026. It is now read-only.

UniquePython/n-body-sim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

N-Body Gravitational Simulation

A real-time 2D gravitational simulation written in C using raylib. Bodies attract each other under Newtonian gravity, merge on collision, and accrete into larger bodies over time.

demo


Features

  • Newtonian gravity with softening to prevent force singularities
  • Leapfrog (Störmer-Verlet) symplectic integration for long-term orbital stability
  • Body merging with conservation of momentum and mass
  • Particle sparks on collision
  • Glow rendering with layered alpha falloff
  • Color scales with body mass (dim red → white)
  • Follow cam — click any body to track it
  • Simulation speed control
  • Pan and zoom

Physics

Most simple simulations use Euler integration — add velocity to position, add acceleration to velocity, repeat. It's first-order and bleeds energy over time, causing orbits to slowly spiral inward or outward.

This simulation uses leapfrog integration, which staggers velocity and position updates by a half-timestep. Leapfrog is symplectic — it conserves a quantity that behaves like energy indefinitely, keeping orbits stable over millions of steps. The cost is identical to Euler; the accuracy over long timescales is dramatically better.

Force calculations use a softening parameter in the denominator (r² + ε²) to prevent the force from blowing up when two bodies get very close.

Bodies are initialized in a rotating disk with tangential velocities derived from the circular orbit formula v = √(GM/r), giving each body the exact speed needed for a stable orbit at its radius.


Building

Requires raylib installed on your system.

git clone https://github.com/UniquePython/n-body-sim
cd n-body-sim
make > /dev/null && bin/n-body

Controls

Input Action
/ Increase / decrease simulation speed
Scroll Zoom in / out
Left drag Pan camera
Right click (body) Follow body
Right click (empty) Unfollow

Parameters

Key constants in nbody.c you can tune:

Constant Default Effect
N_BODIES 15 Number of bodies at start
G 1000.0 Gravitational constant
SUN_MASS 3000.0 Mass of central body
MIN/MAX_ORBIT_DIST 80–350 Initial orbital radius range
EPS 5.0 Softening length
K 1.0 Visual radius scale factor

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors