A complete, interactive guide to the physics concepts powering every game engine — from vectors and integration to collisions and rigid bodies.
Vectors are arrows with a length and a direction. Derivatives are rates of change. Integrals are accumulated totals. Everything else in game physics is built on these three ideas.
struct Vec2 { float x, y; // Construction Vec2(float x = 0, float y = 0) : x(x), y(y) {} // Arithmetic operators Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; } Vec2 operator-(const Vec2& o) const { return {x - o.x, y - o.y}; } Vec2 operator*(float s) const { return {x * s, y * s}; } Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; } // Length and normalization float LengthSq() const { return x*x + y*y; } float Length() const { return std::sqrt(LengthSq()); } Vec2 Normalized() const { float len = Length(); return len > 0.0001f ? Vec2{x/len, y/len} : Vec2{}; } // Dot product: >0 same dir, =0 perp, <0 opposite float Dot(const Vec2& o) const { return x*o.x + y*o.y; } }; // ---Usage--------- Vec2 playerPos = {100.0f, 50.0f}; Vec2 enemyPos = {200.0f, 50.0f}; Vec2 toEnemy = (enemyPos - playerPos ). Normalized(); // Vision cone check: is the enemy in front of the player? Vec2 playerFacing = {1.0f, 0.0f}; // facing right float dot = playerFacing.Dot(toEnemy); if (dot > 0.707f) { // cos(45°) — inside a 90° cone printf("Enemy is in front!\n") };
Integration is how we step physics forward through time. Choose the wrong method and your simulation adds energy out of nowhere — springs explode, orbits spiral outward.
position += velocity * dt;
velocity += accel * dt;
// ↑ uses OLD velocity!
velocity += accel * dt;
position += velocity * dt;
// ↑ uses NEW velocity!
// Game loop with fixed physics step + interpolation constexpr float FIXED_DT = 1.0f / 60.0f; // 60 Hz physics float accumulator = 0.0f; float prevTime = GetTime(); while (running) { float now = GetTime(); float frame = min(now - prevTime, 0.05f); // cap at 50ms prevTime = now; accumulator += frame; // Physics runs in fixed steps — deterministic while (accumulator >= FIXED_DT) { PhysicsStep(FIXED_DT); // semi-implicit Euler inside accumulator -= FIXED_DT; } // Interpolate renders between physics ticks float alpha = accumulator / FIXED_DT; Render(alpha); // lerp prev/curr state } void PhysicsStep(float dt) { for (auto& body : bodies) { // Semi-implicit Euler: velocity first, THEN position body.velocity += body.acceleration * dt; body.position += body.velocity * dt; body.acceleration = {}; // reset — forces recomputed each step } }
Gravity. Drag. Friction. Three forces cover 90% of game physics. Understanding them means understanding why things move — not just that they do.
// Force accumulator — add all forces, divide by mass once per step struct Body { Vec2 position, velocity; Vec2 forceAccum; // reset to zero after each step float mass, invMass; // invMass = 0 for static bodies float restitution = 0.6f; float linearDamping = 0.99f; // multiply vel each step — simple drag void AddForce(Vec2 f) { forceAccum += f; } }; // Per-step: apply forces then integrate void ApplyForces(Body& b, float dt) { if (b.invMass == 0.f) return; // static body // 1. Gravity (applied as force, not direct acceleration) b.AddForce({0.f, b.mass * -9.81f}); // 2. Linear drag — opposes velocity const float k = 0.02f; b.AddForce(b.velocity * -k); // 3. Integrate: semi-implicit Euler Vec2 accel = b.forceAccum * b.invMass; // a = F/m b.velocity += accel * dt; b.position += b.velocity * dt; // 4. Simple damping multiplier (alternative to explicit drag force) b.velocity = b.velocity * b.linearDamping; // 5. Reset accumulator for next frame b.forceAccum = {}; } // Bounce response (1D, along collision normal) float BounceVelocity(float impactVel, float e) { return -impactVel * e; // e=0 → stops, e=1 → full reverse }
Three rules, written down in 1687. Still running every physics engine shipping today. Every Rigidbody component is a compact implementation of all three.
// This is the heart of every physics engine. // Everything else is deciding what totalForce is. void Integrate(Body& b, float dt) { if (b.invMass == 0.f) return; // Newton 2nd: a = F/m Vec2 accel = b.forceAccum * b.invMass; // Semi-implicit Euler b.velocity += accel * dt; b.position += b.velocity * dt; b.forceAccum = {}; } // 3rd law: impulse pairs void ApplyImpulse(Body& a, Body& b, Vec2 impulse) { a.velocity += impulse * a.invMass; b.velocity -= impulse * b.invMass; // equal & opposite }
invMass (1/mass) instead of mass directly. Division is slow; multiply by invMass instead. Static bodies have invMass = 0 — no force moves them.Detecting collisions naively is O(n²) — every object checked against every other. Real engines split this into two phases to stay fast.
| Shape | Cost | Best for | Notes |
|---|---|---|---|
| Sphere / Circle | Cheapest | Characters, projectiles, pickups | Distance check only |
| AABB / Box | Very cheap | Crates, walls, UI buttons | Axis-aligned — no rotation |
| Capsule | Cheap | Humanoid characters | Smooth on stairs and edges |
| Convex hull | Moderate | Vehicles, complex props | GJK algorithm |
| Triangle mesh | Expensive — STATIC ONLY | Terrain, level geometry | Never move a mesh collider |
// Circle vs Circle bool CircleCircle(Vec2 p1, float r1, Vec2 p2, float r2) { float dist2 = (p2-p1).LengthSq(); float rSum = r1 + r2; return dist2 <= rSum * rSum; // no sqrt! } // AABB vs AABB (Axis-Aligned Bounding Box) struct AABB { Vec2 min, max; }; bool AABBvsAABB(const AABB& a, const AABB& b) { if (a.max.x < b.min.x || a.min.x > b.max.x) return false; if (a.max.y < b.min.y || a.min.y > b.max.y) return false; return true; // overlap on both axes } // Circle vs AABB — closest point test bool CircleAABB(Vec2 c, float r, const AABB& b) { Vec2 closest = { clamp(c.x, b.min.x, b.max.x), clamp(c.y, b.min.y, b.max.y) }; return (closest - c).LengthSq() <= r * r; } // Penetration depth (circle vs AABB) Vec2 PenetrationNormal(Vec2 c, float r, const AABB& b) { Vec2 closest = { clamp(c.x, b.min.x, b.max.x), clamp(c.y, b.min.y, b.max.y) }; Vec2 n = c - closest; float d = n.Length(); return d > 0 ? n * ((r - d) / d) : Vec2{0, -r}; }
The everyday tools you'll touch in every Unity / Unreal project.
OnCollisionEnter.
OnTriggerEnter.
Linear motion has a perfect angular mirror. Every concept maps across: force → torque, mass → inertia, velocity → angular velocity. Same equations, different letters.
struct RigidBody { // Linear Vec2 position; Vec2 velocity; Vec2 forceAccum; float mass, invMass; // Angular float angle = 0.f; float angularVelocity = 0.f; float torqueAccum = 0.f; float inertia, invInertia; // Apply force at world-space point void AddForceAtPoint(Vec2 f, Vec2 point) { forceAccum += f; // torque = r × F (2D cross product) Vec2 r = point - position; torqueAccum += r.Cross(f); } }; void IntegrateRigidBody(RigidBody& b, float dt) { if (b.invMass == 0.f) return; // Linear integration Vec2 accel = b.forceAccum * b.invMass; b.velocity += accel * dt; b.position += b.velocity * dt; // Angular integration (same pattern!) float angAccel = b.torqueAccum * b.invInertia; b.angularVelocity += angAccel * dt; b.angle += b.angularVelocity * dt; // Reset accumulators b.forceAccum = {}; b.torqueAccum = 0.f; } // Moment of inertia for a rectangle float RectInertia(float m, float w, float h) { return m * (w*w + h*h) / 12.0f; }
What's actually running under the hood of the engines you use every day — and the most common pitfalls to avoid.
| Engine | Backend | Solver | Notes |
|---|---|---|---|
| Unity | PhysX 5 (3D) / Box2D (2D) | Sequential impulse | Moving to Jolt-style in DOTS |
| Unreal | Chaos Physics | Position-based dynamics | Replaced PhysX in UE5. GPU-friendly |
| Godot | Godot Physics / Jolt | Sequential impulse | Jolt available since 4.4 |
| Roblox | Custom (Spring) | Position-based | Built for massive concurrent sims |
A complete, minimal 2D physics engine in C++ — everything from this course in ~200 lines. Vectors, rigid bodies, forces, integration, and collision response.
// ──────────────────────────────────────────────────────────────────────────── // physics2d.h — Minimal 2D Physics Engine // Covers: Vec2, RigidBody, ForceRegistry, BroadPhase, CollisionSolver // ──────────────────────────────────────────────────────────────────────────── #pragma once #include <vector> #include <cmath> #include <algorithm> // ── 1. Vec2 ────────────────────────────────────────────────────────────────── struct Vec2 { float x = 0, y = 0; Vec2 operator+(Vec2 o) const { return {x+o.x, y+o.y}; } Vec2 operator-(Vec2 o) const { return {x-o.x, y-o.y}; } Vec2 operator*(float s) const { return {x*s, y*s }; } Vec2& operator+=(Vec2 o) { x+=o.x; y+=o.y; return *this; } float LengthSq() const { return x*x + y*y; } float Length() const { return std::sqrt(LengthSq()); } Vec2 Normalized() const { float l=Length(); return l>1e-5f ? *this*(1/l) : Vec2{}; } float Dot(Vec2 o) const { return x*o.x + y*o.y; } float Cross(Vec2 o) const { return x*o.y - y*o.x; } }; // ── 2. RigidBody ────────────────────────────────────────────────────────────── struct RigidBody { Vec2 position, velocity, forceAccum; float mass, invMass; float angle=0, angularVel=0, torqueAccum=0; float inertia, invInertia; float radius = 0.5f; // using circles for simplicity float restitution = 0.6f; float linearDamp = 0.998f; float angularDamp = 0.995f; void SetMass(float m) { mass = m; invMass = m > 0 ? 1.f/m : 0; inertia = 0.5f * m * radius * radius; // solid disk invInertia = inertia > 0 ? 1.f/inertia : 0; } void AddForce(Vec2 f) { forceAccum += f; } void AddForceAtPoint(Vec2 f, Vec2 pt) { forceAccum += f; torqueAccum += (pt - position).Cross(f); } }; // ── 3. Integration (Semi-implicit Euler) ────────────────────────────────────── void Integrate(RigidBody& b, float dt, float gravity) { if (b.invMass == 0.f) return; b.AddForce({0.f, b.mass * gravity}); // gravity (down = +y here) Vec2 accel = b.forceAccum * b.invMass; // Newton 2nd: a = F/m b.velocity += accel * dt; // semi-implicit: vel first b.position += b.velocity * dt; // then position b.velocity = b.velocity * b.linearDamp; float angAccel = b.torqueAccum * b.invInertia; b.angularVel += angAccel * dt; b.angle += b.angularVel * dt; b.angularVel = b.angularVel * b.angularDamp; b.forceAccum = {}; b.torqueAccum = 0.f; } // ── 4. Collision Detection + Response ──────────────────────────────────────── struct Contact { Vec2 normal; float depth; }; bool CircleCircle(const RigidBody& a, const RigidBody& b, Contact& c) { Vec2 d = b.position - a.position; float dist = d.Length(); float rSum = a.radius + b.radius; if (dist >= rSum) return false; c.normal = dist > 1e-5f ? d * (1.f/dist) : Vec2{0,1}; c.depth = rSum - dist; return true; } void ResolveCollision(RigidBody& a, RigidBody& b, const Contact& c) { // Positional correction — push apart (avoids sinking) float invMassSum = a.invMass + b.invMass; if (invMassSum < 1e-5f) return; Vec2 corr = c.normal * (c.depth / invMassSum); a.position = a.position - corr * a.invMass; b.position = b.position + corr * b.invMass; // Impulse response (Newton 3rd: equal & opposite) Vec2 relVel = b.velocity - a.velocity; float velAlongNormal = relVel.Dot(c.normal); if (velAlongNormal > 0) return; // separating float e = std::min(a.restitution, b.restitution); float j = -(1.f + e) * velAlongNormal / invMassSum; Vec2 impulse = c.normal * j; a.velocity = a.velocity - impulse * a.invMass; // Newton 3rd b.velocity = b.velocity + impulse * b.invMass; } // ── 5. World ─────────────────────────────────────────────────────────────────── struct World { std::vector<RigidBody> bodies; float gravity = 9.81f; void Step(float dt) { for (auto& b : bodies) Integrate(b, dt, gravity); // Broad phase (naive O(n²) — replace with BVH for production) for (size_t i = 0; i < bodies.size(); ++i) for (size_t j = i+1; j < bodies.size(); ++j) { Contact c; if (CircleCircle(bodies[i], bodies[j], c)) ResolveCollision(bodies[i], bodies[j], c); } } };