This is an interactive 2D simulation of gravitational interaction between objects with adjustable parameters.
PyGravitySimulator
├── .github/ # Workflows (CI)
├── tests/ # Tests (Unit, UI)
├── resources/ # Resourses (Icons, Textures etc.)
├── gravity_simulator/ # Main py package
├── .flake8 # Settings for flake8
├── .pylintrc # Settings for pylint
├── README.md # This file
└── readme.ru.md # Ru-version for this file
pip install pygame
git clone https://github.com/Ewerall/PyGravitySimulator.git
python -m gravity_simulator.main
The simulator uses Newton's classical law of universal gravitation with regularization to prevent numerical instability:
Basic formulas:
dx = p₂.x - p₁.x
dy = p₂.y - p₁.y
r² = dx² + dy²
r = √(r² + ε²)
Where:
dx
,dy
- components of the distance between objectsr
- regularized distanceε
- softening parameter, preventing infinite forces at small distances
Gravitational force:
F = G·(m₁·m₂)/(r² + ε²)^(3/2)·(dx, dy)
Or in component form:
Fₓ = G·m₁·m₂·dx/(r²·r)
Fᵧ = G·m₁·m₂·dy/(r²·r)
Where:
G
- gravitational constantm₁
,m₂
- masses of objectsFₓ
,Fᵧ
- force components
Particle motion is calculated using the Euler method:
Acceleration:
aₓ = Fₓ/m
aᵧ = Fᵧ/m
Velocity:
vₓ(t+dt) = vₓ(t) + aₓ·dt
vᵧ(t+dt) = vᵧ(t) + aᵧ·dt
Position:
x(t+dt) = x(t) + vₓ(t+dt)·dt
y(t+dt) = y(t) + vᵧ(t+dt)·dt
Where:
dt
- time stepa
- accelerationv
- velocityx
,y
- coordinates
Collision detection
dx = p₂.x - p₁.x
dy = p₂.y - p₁.y
r² = dx² + dy²
r = √r²
if r < (R₁ + R₂), a collision has occurred
Where:
R₁
,R₂
- radii of objects
When particles collide, they merge while conserving momentum and recalculating the center of mass:
Total mass:
M = m₁ + m₂
Velocity after merging (momentum conservation):
vₓ = (m₁·v₁ₓ + m₂·v₂ₓ)/M
vᵧ = (m₁·v₁ᵧ + m₂·v₂ᵧ)/M
Position after merging (center of mass):
x = (m₁·x₁ + m₂·x₂)/M
y = (m₁·y₁ + m₂·y₂)/M
Radius of the resulting object (for 2D):
R = √M
This follows from the fact that in 2D, mass is proportional to the area of a circle: M ∝ πR² ⇒ R ∝ √M