Reading — step 1 of 5
Read
~2 min readMath & Integration
Numerical Integration
Bodies have:
- Position p (Vec2).
- Velocity v (Vec2).
- Acceleration a (Vec2).
- Mass m (scalar).
Newton's second law: F = m * a → a = F / m.
To advance the simulation by time dt:
Euler integration (simplest, inaccurate):
python
Problems: gains energy over time. Orbits spiral outward. Used in cheap games.
Symplectic Euler (semi-implicit, simple, stable):
python
Better than basic Euler. Used in many physics engines.
Verlet integration:
- Stores previous position instead of velocity.
- More numerically stable for constraints.
- Used by Box2D internally.
python
Runge-Kutta 4 (RK4):
- Higher order; more accurate.
- Used in scientific simulations.
- 4x as expensive per step.
- Probably overkill for games.
For games: symplectic Euler at fixed timestep is the practical default.
Fixed timestep:
python
Why fixed?
- Deterministic: same input → same output.
- Stable: timestep can't blow up at variable rates.
- Networking: simulations stay in sync.
Variable dt = simulation drift over time.
Forces:
- Gravity: F = m * g (constant 9.8 m/s² on Earth).
- Spring: F = -k * x (Hooke's law).
- Drag: F = -c * v (proportional to velocity).
- Player input: arbitrary.
python
Sum forces, then integrate. Reset force to zero after each step.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…