Physics · course

Physics for
Game Development

A complete, interactive guide to the physics concepts powering every game engine — from vectors and integration to collisions and rigid bodies.

Math Foundations Integration Forces Newton's Laws Collision Detection Rigid Bodies
Section 01

Math Foundations

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.

Vector Operations
➕
Add / Subtract
Combine motions: v₁ + v₂ = resultant displacement
v1 + v2
✕
Scale
Multiply by a scalar — longer, shorter, or flipped
s · v
→
Normalize
Unit vector — length = 1, pure direction
v / |v|
·
Dot Product
How aligned are two vectors? Returns a scalar
a·b = |a||b|cosθ
✕
Cross Product (3D)
Returns a vector perpendicular to both inputs
a × b = n
|v| = √(x² + y²)   // magnitude (length)
v̂ = v / |v|      // normalized
a · b = ax·bx + ay·by // dot product 2D
⬡ Interactive Vector Demo — drag the tips
a=(3,2) b=(−1,3)
💡
Dot product sign rule: >0 same direction · =0 perpendicular · <0 opposite. Used in AI vision cones, backface culling, lighting calculations.
Vector2 — C++ ImplementationC++
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") };
 

Position · Velocity · Acceleration

Position
x
Where something is in space. A point, not a direction.
x = (px, py)
Velocity
v
How fast position changes. dx/dt — the derivative of position.
v = Δx / Δt
Acceleration
a
How fast velocity changes. dv/dt — the derivative of velocity.
a = Δv / Δt
💡
Derivative — rate of change How fast is it changing? The slope of a curve at any point. In physics we take derivatives of position over time to get velocity, and derivatives of velocity over time to get acceleration.

Integral

How much accumulates over time
  • Add up velocity → position
  • Add up acceleration → velocity
  • Add up force × time → impulse
💡
Integral — accumulation over time How much has accumulated? The area under a curve. We integrate acceleration over time to recover velocity, and velocity over time to recover position. This is how physics engines advance the simulation each frame.
Section 02

Time & Integration

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.

⚠ Variable Timestep
Pro: Smooth visuals, renders at GPU speed.

Con: Same scene + different framerate = different physics results. Non-deterministic.

Use for: Animation, camera, UI only.
✓ Fixed Timestep
Pro: Deterministic — same input always gives same output. Safe for replays and networking.

Con: Stale renders without interpolation.

Use for: All physics simulation.
⚠
Explicit Euler (position += vel * dt, THEN vel += accel * dt) adds energy over time. Flip the order to get semi-implicit Euler — massively more stable.
Explicit Euler (broken)
position += velocity * dt;
velocity += accel    * dt;
// ↑ uses OLD velocity!
Semi-implicit (stable)
velocity += accel    * dt;
position += velocity * dt;
// ↑ uses NEW velocity!
⬡ Euler vs Semi-Implicit — energy comparison
Spring stiffness 1.0
💡Why does swapping two lines fix it?
By updating velocity before position, the position step uses the freshly computed velocity — one that already reflects the current forces. This keeps the update in sync with how forces actually drive the system, and the result conserves energy almost perfectly for typical game scenarios.
Fixed Timestep Game Loop — C++C++
// 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
    }
}
Section 03

Forces in Practice

Gravity. Drag. Friction. Three forces cover 90% of game physics. Understanding them means understanding why things move — not just that they do.

Gravity F = m · g
Constant downward acceleration. In games g ≈ 9.81 m/s² but you almost always tune it — real gravity feels too slow for action games. Try 20–30 m/s².
Drag F = −k · v
Slows objects opposing their velocity. Linear drag (−kv) works at low speeds. Quadratic drag (−kv|v|) for fast-moving objects like projectiles or skydiving.
Friction F ≤ μ · N
Static friction prevents motion (μs ≈ 0.3–1.0). Kinetic friction opposes sliding (always less than static). N is the normal force — the perpendicular contact force.
Restitution e = v_out / v_in
e = 0 → dead stop (wet clay). e = 1 → perfectly elastic (idealized). Basketball ≈ 0.3. Superball ≈ 0.8.
⬡ Force Comparison — see the difference
Gravity 20 m/s²
Drag coeff 0.020
Restitution 0.60
Forces — C++ accumulation patternC++
// 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
}
Section 04

Newton's Laws

Three rules, written down in 1687. Still running every physics engine shipping today. Every Rigidbody component is a compact implementation of all three.

1st
Inertia
An object stays at rest — or moves at constant velocity — unless a net force acts on it. A spaceship in vacuum never stops on its own.
ΣF = 0 → a = 0
2nd
F = m · a
Net force equals mass times acceleration. Double the mass → need double the force to accelerate the same way.
a = ΣF / m
3rd
Action / Reaction
For every force there is an equal and opposite force. Recoil. Rocket exhaust. Why the floor pushes back when you stand on it.
F₁₂ = −F₂₁
⬡ Newton's 2nd Law — mass vs acceleration
Force 150 N
Mass A 5 kg
Mass B 15 kg
Newton's 2nd — C++C++
// 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
}
💡
Store invMass (1/mass) instead of mass directly. Division is slow; multiply by invMass instead. Static bodies have invMass = 0 — no force moves them.
Section 05

Collision Detection

Detecting collisions naively is O(n²) — every object checked against every other. Real engines split this into two phases to stay fast.

Broad Phase — "could these collide?"
Cheap, approximate. Eliminates obvious non-colliders quickly. Produces a small list of candidate pairs for narrow phase.
▦
Uniform spatial grid
Hash objects into grid cells, only check same/adjacent cells
◫
Quadtree / Octree
Recursive spatial subdivision, adapts to object density
⊞
BVH (Bounding Volume Hierarchy)
Tree of AABBs — modern engines default to this
Narrow Phase — "are they actually touching?"
Exact, expensive. Returns contact point, collision normal, and penetration depth. Run only on candidate pairs from broad phase.
●
Circle ↔ Circle
distance(a,b) < r_a + r_b — cheapest possible test
■
AABB ↔ AABB
Overlap on all axes — no overlap on any axis = no collision
◆
Convex shapes → SAT / GJK
Separating Axis Theorem — if any axis separates them, they're not colliding
Collider Shape Costs
ShapeCostBest forNotes
Sphere / CircleCheapestCharacters, projectiles, pickupsDistance check only
AABB / BoxVery cheapCrates, walls, UI buttonsAxis-aligned — no rotation
CapsuleCheapHumanoid charactersSmooth on stairs and edges
Convex hullModerateVehicles, complex propsGJK algorithm
Triangle meshExpensive — STATIC ONLYTerrain, level geometryNever move a mesh collider
⬡ Circle vs AABB — live collision test
Move the circle with your mouse
Collision Tests — C++C++
// 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};
}
⚠
Tunneling (bullet-through-paper): A fast object can jump entirely through a thin wall in one frame. Fix with Continuous Collision Detection (CCD) — test a swept capsule along the motion path — but only enable CCD on fast-moving bodies (bullets, vehicles). It's expensive.
Everyday Tools

Triggers, layers, and the collision matrix

The everyday tools you'll touch in every Unity / Unreal project.

Trigger vs Collider
Collider — physically blocks. Pushes things. OnCollisionEnter.
Trigger — passes through. Just reports overlap. OnTriggerEnter.
Use triggers for: pickups, doors, damage volumes, checkpoints.
Layers & collision matrix
Tag every collider with a layer (Player, Enemy, Bullet…).
Then declare which layers can collide with which:
✓ Bullet × Enemy
✗ Bullet × Bullet
✗ Player × Pickup (use trigger instead)
Section 06

Rotation & Rigid Bodies

Linear motion has a perfect angular mirror. Every concept maps across: force → torque, mass → inertia, velocity → angular velocity. Same equations, different letters.

Linear
Position x
Velocity v
Acceleration a
Force F
Mass m
F = m · a
↔
↔
↔
↔
↔
↔
Angular
Angle θ
Angular velocity ω
Angular accel α
Torque τ
Moment of inertia I
τ = I · α
⬡ Rigid Body — forces applied off-center create torque
Inertia 1.0
Rigid Body — C++ structC++
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;
}
Section 07

Engine Reality

What's actually running under the hood of the engines you use every day — and the most common pitfalls to avoid.

Physics backends by engine
EngineBackendSolverNotes
UnityPhysX 5 (3D) / Box2D (2D)Sequential impulseMoving to Jolt-style in DOTS
UnrealChaos PhysicsPosition-based dynamicsReplaced PhysX in UE5. GPU-friendly
GodotGodot Physics / JoltSequential impulseJolt available since 4.4
RobloxCustom (Spring)Position-basedBuilt for massive concurrent sims
Scale issues
Unity's PhysX assumes 1 unit = 1 m. A 100 m box makes physics weird. Always build at real-world scale.
Wrong timestep
Below 1/120s → wasted CPU. Above 1/30s → tunneling. Target 1/60s. Never use real delta time for physics.
Mesh-on-mesh
Moving mesh colliders are catastrophically expensive. Use convex hulls or compound primitives instead.
Forgotten interpolation
Physics in FixedUpdate. Without render interpolation between ticks, motion looks jittery at 60fps visuals.
Forces vs velocities
AddForce respects mass. SetVelocity ignores it. Mixing them causes unpredictable jerky motion.
CCD everywhere
Continuous collision detection is expensive. Enable only on fast objects: bullets and vehicles.
Final Code

Putting It All Together

A complete, minimal 2D physics engine in C++ — everything from this course in ~200 lines. Vectors, rigid bodies, forces, integration, and collision response.

⬡ Complete physics demo — all systems running
Gravity 400
Restitution 0.65
physics2d.h — Complete Minimal 2D Physics EngineC++
// ────────────────────────────────────────────────────────────────────────────
// 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);
        }
    }
};