Free reference for game makers

Game Mechanics & Physics Lab

Learn how games really work by playing with them. Each mechanic below has a live demo you can poke, a plain-English explanation, and short code snippets in JavaScript and Python (Pygame) that you can copy straight into your own project.

New to the math? Words with a dotted underline explain themselves: hover, tap or tab to them.

How to use these snippets (conventions and starter project)
  • Units: positions are in pixels, speeds in pixels per second, and dt is the seconds since the last frame.
  • Y points down on screen (in the browser canvas and in Pygame), so gravity is a positive number and “up” is negative.
  • Pygame: snippets use pygame.Vector2 (pygame 2.x). Most are written as the body of your game loop or as a small function you call from it.
  • The demos are real: they run the same math as the snippets next to them. Use Pause and Step to go one frame at a time.

JavaScript starter

<canvas id="game" width="640" height="360"></canvas>
<script>
  const ctx = document.getElementById('game').getContext('2d');
  let last = performance.now();

  function update(dt) { /* paste a snippet here */ }
  function draw(ctx)  { ctx.clearRect(0, 0, 640, 360); /* draw things */ }

  function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.05);   // seconds
    last = now;
    update(dt);
    draw(ctx);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
</script>

Python (Pygame) starter

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
running = True

while running:
    dt = min(clock.tick(60) / 1000, 0.05)       # seconds
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # paste a snippet here (update using dt)

    screen.fill((10, 10, 15))
    # draw things
    pygame.display.flip()

pygame.quit()

Basic

The building blocks: loops, movement, gravity and simple hit tests.

BasicFoundations

The Game Loop & Delta Time

Every game is a loop: read input, update the world, draw. keeps it running at the same on every machine.

Drag the FPS slider. The top box speeds up and slows down; the bottom one never does.

A game runs the same three steps over and over: handle input, update the world, draw the . How often that happens () depends on the player's hardware, so you can't assume it is always 60.

If you move an object a fixed amount per frame, it runs fast on a 144 monitor and crawls on a slow laptop. Instead, measure the time since the last frame (delta time, or dt) and multiply every rate of change by it. Now speeds are in " per second" and the game plays identically everywhere.

Key ideadistance = speed × dt. Store speeds per second, then scale by the seconds that passed this frame.
Watch out dt (for example to 0.05 s). After a lag spike or a window , a huge dt can teleport objects through walls.
let last = performance.now();
const speed = 160;               // pixels per SECOND

function frame(now) {
  // seconds since the previous frame, clamped after lag spikes
  const dt = Math.min((now - last) / 1000, 0.05);
  last = now;

  // BAD:  player.x += 3;            (depends on the frame rate)
  // GOOD: speed per second x seconds this frame
  player.x += speed * dt;

  draw();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
BasicFoundations

Vectors & Direction

A is just a direction plus a length. fixes the classic "diagonal movement is faster" bug.

Left: raw input. Right: normalized. Watch how far each dot gets in one second.

A 2D vector is a pair of numbers (x, y). It can be a position, a , or a direction. Its length () is √(x² + y²), which is the in disguise.

When a player holds Right + Down, the input vector is (1, 1). Its length is 1.41, not 1, so a character using it directly moves 41% faster on diagonals. Normalizing means dividing a vector by its own length so the result always has length 1: it keeps the direction and throws away the size. Then you multiply by the you actually want.

Key ideadirection = input / length(input). velocity = direction × speed.
Watch outNever . When no key is pressed the length is 0, so check before normalizing.
// Build the input direction from the keys
let dx = (keys.right ? 1 : 0) - (keys.left ? 1 : 0);
let dy = (keys.down ? 1 : 0) - (keys.up ? 1 : 0);

// Diagonals have length sqrt(2) = 1.41, so they would be 41% faster.
// Normalize: divide by the length so it is always exactly 1.
const len = Math.hypot(dx, dy);
if (len > 0) {
  dx /= len;
  dy /= len;
}

player.x += dx * speed * dt;
player.y += dy * speed * dt;
BasicMovement

Velocity

is how fast something moves and in which direction. Position changes by velocity × time, every .

Click anywhere to launch the ball toward that point. The dashed lines are vx and vy.

is a single number. Velocity is speed plus direction, stored as a (vx, vy): how many the object moves per second along each axis. Keeping x and y separate makes it easy to react to walls: flip only the component that hit.

To turn an angle and a speed into a velocity use for x and sine for y. Each frame you "": position += velocity × . This is the foundation of almost every moving thing in a game.

If you have heard the word : the rate at which position changes is called a , and adding those changes up frame by frame is integration. You use a little calculus every time you write position += velocity × dt, without doing any of the hard math.

Key ideavx = cos(angle) × speed, vy = sin(angle) × speed. position += velocity × dt.
Watch outOn screens y grows downward, so an angle of 90° points down, not up.
const ball = { x: 100, y: 100, vx: 0, vy: 0 };

// Velocity from an angle and a speed (pixels per second)
const angle = 30 * Math.PI / 180;     // radians
const speed = 200;
ball.vx = Math.cos(angle) * speed;
ball.vy = Math.sin(angle) * speed;

function update(dt) {
  ball.x += ball.vx * dt;             // position changes by velocity x time
  ball.y += ball.vy * dt;

  // hitting a wall flips only that axis
  if (ball.x < 0 || ball.x > width)  ball.vx = -ball.vx;
  if (ball.y < 0 || ball.y > height) ball.vy = -ball.vy;
}
BasicMovement

Acceleration

changes over time. It is what makes movement feel heavy, smooth or snappy.

It drives itself. Hold the mouse on the right/left half of the canvas (or press ← →) to take over.

Velocity is how position changes; acceleration is how velocity changes. Instead of setting the directly, you push it: velocity += acceleration × , then position += velocity × dt. The object eases into motion instead of snapping to full speed.

The graph below is velocity over time. Its slope is the acceleration. A steep line feels sporty, a shallow one feels like a heavy truck. Pair it with a speed cap, otherwise the object accelerates forever.

has names for this chain: velocity is the of position, and acceleration is the derivative of velocity. Going the other way, adding acceleration into velocity and velocity into position, is .

Key ideavelocity += acceleration × dt; position += velocity × dt (in that order).
Watch outUpdate velocity first, then position. This "" order is more stable than the reverse.
const car = { x: 0, v: 0 };      // position, velocity
const accel = 200;                // pixels per second, per second
const maxSpeed = 300;

function update(dt) {
  let a = 0;
  if (keys.right) a =  accel;
  if (keys.left)  a = -accel;

  car.v += a * dt;                // acceleration changes velocity
  car.v = Math.max(-maxSpeed, Math.min(maxSpeed, car.v));  // speed cap
  car.x += car.v * dt;            // velocity changes position
}
BasicMovement

Friction & Drag

Slow things down smoothly. fades proportionally; removes a fixed amount until the object stops.

Click anywhere to flick the puck toward that point.

Without something to slow it down, an object keeps its forever. There are two common ways to bleed speed. Drag (air resistance) removes a percentage of the speed each second, so fast objects slow quickly and slow ones glide for a long time. Friction removes a fixed amount per second, so the object comes to a hard stop.

Many tutorials write velocity *= 0.98 every . That is : at 144 you apply it 144 times a second instead of 60. Using (-drag × ) gives the same result at any frame rate.

Key ideaDrag: v *= exp(−k·dt). Friction: speed = max(0, speed − f·dt).
Watch outWhen applying friction, never let the speed go below zero or the object will creep backwards.
// DRAG: lose a percentage of speed each second (smooth, never quite stops)
const k = Math.exp(-drag * dt);          // frame-rate independent
puck.vx *= k;
puck.vy *= k;

// FRICTION: lose a fixed amount of speed each second (stops completely)
const speed = Math.hypot(puck.vx, puck.vy);
if (speed > 0) {
  const newSpeed = Math.max(0, speed - friction * dt);
  puck.vx *= newSpeed / speed;
  puck.vy *= newSpeed / speed;
}
BasicMovement

Gravity & Jumping

is constant downward . Pick the jump height you want and derive the launch from it.

It jumps on its own. Press Space / ↑ or click to jump yourself.

Gravity is just acceleration that always points down: vy += gravity × . Jumping sets vy to a negative (upward) value once, and gravity gradually turns it around. The arc you see is a .

Designers think in jump heights, not launch speeds. Solve for it: v₀ = √(2·g·h). Now you can tweak gravity for feel without breaking the jump height. Many platformers also pull the player down harder than they go up (a "fall multiplier"), which feels snappier while keeping the same peak.

Key ideav₀ = √(2 · gravity · jumpHeight). Each : vy += gravity × dt, y += vy × dt.
Watch outReset vy to 0 when you land. If you don't, gravity keeps building and the player falls through the floor. The real peak can also differ from your target by a few , because the game moves in frame-sized steps.
const gravity = 1400;                 // px/s^2 (positive = down)
const jumpHeight = 110;               // pixels
const jumpSpeed = Math.sqrt(2 * gravity * jumpHeight);   // v0 = sqrt(2gh)

function update(dt) {
  if (jumpPressed && player.onGround) {
    player.vy = -jumpSpeed;           // negative = up
    player.onGround = false;
  }

  // fall faster than you rise: snappier feel, same peak height
  const g = player.vy > 0 ? gravity * fallMultiplier : gravity;
  player.vy += g * dt;
  player.y += player.vy * dt;

  if (player.y >= groundY) {          // landed
    player.y = groundY;
    player.vy = 0;
    player.onGround = true;
  }
}
BasicMovement

Projectile Motion

Arrows, grenades and cannonballs: constant horizontal plus pulling the vertical speed. Predict the whole arc before firing.

Click anywhere to aim and fire from the cannon. The dotted line is the predicted path.

A projectile's x and y motion are independent. Horizontally nothing changes (no air), vx stays constant. Vertically gravity adds to vy every . Combined, you get a .

Because the path is a formula, you can draw it before the player fires: position(t) = start + v·t + ½·g·t². That is how aiming guides in Angry Birds-style games work. Use it for AI too, to ask "will this shot reach the target?" without simulating it.

Key ideax(t) = x₀ + vx·t, y(t) = y₀ + vy·t + ½·g·t² (vy is negative going up). On flat ground: Range = v²·(2θ) / g.
Watch outThe best angle for distance is 45° only on flat ground. Hit a higher or lower target and the ideal angle changes.
// Launch: split the speed into x and y using the angle
const angle = 45 * Math.PI / 180;
ball.vx =  Math.cos(angle) * power;
ball.vy = -Math.sin(angle) * power;   // negative = up

function update(dt) {
  ball.vy += gravity * dt;            // gravity only touches vy
  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;
}

// Predict the arc without simulating: x = x0 + vx*t,  y = y0 + vy*t + 1/2*g*t^2
function pointAt(t) {
  return {
    x: x0 + vx * t,
    y: y0 + vy * t + 0.5 * gravity * t * t,
  };
}
BasicPhysics

Bouncing & Restitution

When something hits a surface, flip its and keep a fraction of the . That fraction is the bounciness.

Click to drop the ball from that spot. Dots mark each bounce peak.

To bounce, reverse the velocity component that points into the surface and multiply it by the (a number from 0 to 1). A value of 1 is a perfect super-ball that bounces forever, 0.5 is a basketball, 0 is a lump of clay that sticks.

Each bounce loses energy, so the peaks form a smooth decay. Height scales with the square of the speed, so a restitution of 0.8 means the next bounce reaches only 64% of the previous height. Always include a stopping threshold, otherwise tiny endless bounces will jitter forever.

Key ideavy = −vy × restitution. Next bounce height = previous height × restitution².
Watch outPush the ball back above the floor before reversing velocity, or it can get stuck vibrating inside the floor.
const restitution = 0.75;             // 0 = no bounce, 1 = perfect bounce

function update(dt) {
  ball.vy += gravity * dt;
  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;

  if (ball.y + ball.r > floorY) {
    ball.y = floorY - ball.r;           // put it back on top of the floor
    ball.vy = -ball.vy * restitution;   // reverse and lose some energy

    if (Math.abs(ball.vy) < 40) {       // too slow to matter: come to rest
      ball.vy = 0;
    }
  }
}
BasicCollision

Box Collision (AABB)

The workhorse of 2D games: are two axis-aligned rectangles overlapping? Four comparisons answer it.

Move the mouse (or drag on touch) to move box A. Watch the four tests flip.

stands for axis-aligned bounding box: a rectangle whose sides line up with the screen axes. Two boxes overlap only if they overlap on the x axis AND on the y axis at the same time.

On one axis, they overlap when each box starts before the other one ends. So the test is four simple comparisons, no and no . Even when your aren't rectangles, a slightly shrunken box (a "hitbox") is usually the fastest, fairest way to detect hits.

Key ideaA.left < B.right AND A.right > B.left AND A.top < B.bottom AND A.bottom > B.top.
Watch outSprites are drawn from their top-left corner, but physics often tracks the center. Mixing the two up is the #1 cause of "my hitbox is offset" bugs.
function overlaps(a, b) {
  return (
    a.x < b.x + b.w &&      // A's left edge is left of B's right edge
    a.x + a.w > b.x &&      // A's right edge is right of B's left edge
    a.y < b.y + b.h &&      // A's top is above B's bottom
    a.y + a.h > b.y         // A's bottom is below B's top
  );
}

const player = { x: 100, y: 100, w: 32, h: 48 };
const coin   = { x: 120, y: 130, w: 16, h: 16 };

if (overlaps(player, coin)) {
  score += 1;               // collected!
}
BasicCollision

Circle Collision

Two circles touch when the distance between their centers is smaller than the sum of their radii.

Move the mouse to drag circle A. The rings show each radius laid along the center line.

Circles are great hitboxes for balls, bullets, pickups and characters that can turn: they look the same from every angle. The test is one distance comparison.

are comparatively slow, and you don't need one: comparing distance with squared radii gives the same answer. That matters when you check thousands of pairs per . Take the square root only when you also need the real distance (for example, to push the circles apart).

Key ideadistance² < (r1 + r2)². Overlap depth = (r1 + r2) − distance.
Watch outIf both centers are at exactly the same point, the direction between them is undefined (). Pick any default direction.
function circlesOverlap(a, b) {
  const dx = b.x - a.x;
  const dy = b.y - a.y;
  const radii = a.r + b.r;
  // compare SQUARED values: no slow square root needed
  return dx * dx + dy * dy < radii * radii;
}

// When you need the real numbers (for pushing apart)
const dist = Math.hypot(b.x - a.x, b.y - a.y);
const depth = a.r + b.r - dist;       // how far they overlap

Standard

The tools nearly every game uses: collision response, aiming, cameras, effects and game feel.

StandardCollision

Circle vs. Box

Find the point on the rectangle closest to the circle's center. If it is closer than the radius, they touch.

Move the circle around the box, especially near its corners. The yellow dot is the closest point.

Mixed shapes are everywhere: a ball against a brick, a bullet against a wall, a character circle against a platform. The trick is to ask: "which point of the rectangle is nearest to the circle's center?"

That point is found by the center's x and y into the rectangle's range. If the center is inside the rectangle, clamping returns the center itself (distance 0). Then it's just a circle-vs-point distance check.

Key ideaclosest = clamp(center, rect.min, rect.max). Hit if distance(center, closest) < radius.
function circleHitsRect(c, r) {
  // closest point on the rectangle to the circle's center
  const closestX = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const closestY = Math.max(r.y, Math.min(c.y, r.y + r.h));

  const dx = c.x - closestX;
  const dy = c.y - closestY;
  return dx * dx + dy * dy < c.r * c.r;
}
StandardCollision

Collision Response: Sliding

Detecting a hit is half the job. To get smooth sliding along walls, move and resolve one axis at a time.

Move the mouse to steer (or use arrow keys / WASD). Turn "Slide" off to see the sticky version.

The naive fix when a move would hit a wall is to cancel the whole move. That makes the player stick to walls as soon as they touch them diagonally. It is the reason many beginner games feel "sticky".

The standard solution is to separate the axes: move on x, push out of anything you now overlap on x, then move on y and push out on y. Moving right into a wall only stops the x motion; the y motion continues, so the player slides along the wall. This also works for tiles and platformers.

Key ideaMove X → resolve X → move Y → resolve Y. Push out toward the side you came from.
Watch outResolve against the direction of travel (moving right: snap to the wall's left edge). Pushing along the shortest overlap instead can teleport you through thin walls.
function move(player, vx, vy, dt, walls) {
  // 1) horizontal
  player.x += vx * dt;
  for (const w of walls) {
    if (overlaps(player, w)) {
      if (vx > 0) player.x = w.x - player.w;       // hit its left side
      else if (vx < 0) player.x = w.x + w.w;       // hit its right side
    }
  }

  // 2) vertical (uses the already-corrected x)
  player.y += vy * dt;
  for (const w of walls) {
    if (overlaps(player, w)) {
      if (vy > 0) player.y = w.y - player.h;       // landed on top
      else if (vy < 0) player.y = w.y + w.h;       // bumped its underside
    }
  }
}
StandardCollision

Raycasting & Line of Sight

Shoot an invisible ray and find the first thing it hits. Used for lasers, hitscan bullets, line-of-sight and dynamic lighting.

Move the mouse: it is the light source. Narrow the spread to get a flashlight cone.

A ray has an origin and a direction. To test it against a wall (a ) you solve for where origin + t·direction meets the segment. If t ≥ 0 (in front of you) and the hit lies on the segment (0 ≤ u ≤ 1), it's a hit; keep the smallest t among all walls to get the closest one.

Fire many rays in a fan and connect their hit points to get a visibility polygon: exactly what a guard "sees" or what a torch lights up. A single ray is enough for hitscan weapons or to check whether anything blocks the path between an enemy and the player.

Key ideapoint = origin + t · direction. Keep the hit with the smallest t ≥ 0.
Watch out rays and segments make the 0. Skip them, or you will get positions.
function castRay(origin, dir, walls) {
  let closest = null;
  for (const w of walls) {                       // each wall is a segment
    const sx = w.x2 - w.x1, sy = w.y2 - w.y1;
    const denom = dir.x * sy - dir.y * sx;
    if (Math.abs(denom) < 1e-9) continue;        // parallel: never meet

    const t = ((w.x1 - origin.x) * sy - (w.y1 - origin.y) * sx) / denom;
    const u = ((w.x1 - origin.x) * dir.y - (w.y1 - origin.y) * dir.x) / denom;

    // t >= 0: in front of us.  0 <= u <= 1: on the wall segment.
    if (t >= 0 && u >= 0 && u <= 1 && (!closest || t < closest.t)) {
      closest = { t, x: origin.x + dir.x * t, y: origin.y + dir.y * t };
    }
  }
  return closest;                                // null = nothing hit
}

// Line of sight: a fan of rays
for (let i = 0; i < rays; i++) {
  const a = (i / rays) * Math.PI * 2;
  hits.push(castRay(origin, { x: Math.cos(a), y: Math.sin(a) }, walls));
}
StandardMovement

Rotation & Aiming

Point at things with , turn toward them at a limited , and fire along the facing direction.

Move the mouse. The turret turns at a limited speed and only fires when it is lined up.

atan2(dy, dx) converts a direction into an angle, so it answers "which way do I need to face to look at that point?". Going the other way, (angle) and sin(angle) turn an angle back into a direction, which you use to fire bullets or move forward.

Snapping instantly to the target looks robotic. Instead, rotate by at most turnSpeed × each . The trick is the shortest turn: the difference between two angles must be wrapped into the range −π…π, otherwise a turret at 350° aiming at 10° swings all the way around the long way.

Key ideatarget = atan2(dy, dx). diff = wrap(target − angle). angle += (diff, ±turnSpeed·dt).
Watch outAngles wrap around. Never subtract two raw angles and use the result without wrapping it first.
// Which way should we face?
const target = Math.atan2(mouse.y - turret.y, mouse.x - turret.x);

// Shortest signed difference, wrapped into -PI..PI
let diff = target - turret.angle;
diff = Math.atan2(Math.sin(diff), Math.cos(diff));

// Turn toward it, but no faster than turnSpeed (radians/second)
const maxTurn = turnSpeed * dt;
turret.angle += Math.max(-maxTurn, Math.min(maxTurn, diff));

// Fire along the facing direction
bullet.vx = Math.cos(turret.angle) * 420;
bullet.vy = Math.sin(turret.angle) * 420;
StandardGame feel

Lerp, Smoothing & Easing

Blend between two values for smooth cameras, UI and animation. curves change the feel of the same movement.

Top: the circle chases the target (move the mouse in the top half). Bottom: pick an easing curve.

(linear interpolation) returns a value part of the way from a to b: a + (b − a) × t. With t = 0.5 you get the midpoint. Calling it every with a small t makes something "chase" its target and slow down as it gets close: great for cameras and followers.

For a follower that behaves the same at every , use t = 1 − (− × ). For animations that have a start and end time, feed the progress (0 to 1) through an easing function first. Ease-in starts slow, ease-out ends slow, "back" overshoots the target and then settles, and "bounce" rebounds like a dropped ball.

Key idealerp(a, b, t) = a + (b − a)·t. chase: t = 1 − exp(−k·dt).
Watch outWriting x = lerp(x, target, 0.1) every frame is not frame-rate independent. At 144 FPS it chases more than twice as fast as at 60.
const lerp = (a, b, t) => a + (b - a) * t;

// 1) Smooth follow that behaves the same at any frame rate
const t = 1 - Math.exp(-smoothing * dt);
follower.x = lerp(follower.x, target.x, t);
follower.y = lerp(follower.y, target.y, t);

// 2) Timed animation with easing
const easeOutCubic = (u) => 1 - Math.pow(1 - u, 3);

elapsed += dt;
const u = Math.min(elapsed / duration, 1);       // progress 0..1
box.x = lerp(startX, endX, easeOutCubic(u));
StandardGame feel

Camera Follow & Screen Shake

The world is bigger than the screen. Smoothly follow the player, and add punch with a fading shake.

Click (or press Space) to trigger a hit. Use ← → to run yourself; otherwise it patrols.

A 2D camera is just an offset. Every object keeps its world position; when drawing you subtract the camera position. To follow a player, the camera toward (player − half the screen) instead of locking to it, and the motion feels far less jarring.

Screen shake adds impact to explosions and hits. Keep a "trauma" value from 0 to 1 that jumps up on impact and fades quickly. Shake by random offsets scaled by trauma : the squaring makes big hits violent and small ones subtle, and the shake dies away smoothly rather than stopping abruptly.

Key ideascreen = world − camera. camera → player − screenCenter (lerped). offset = random × trauma².
Watch outApply the shake offset only when drawing. If you add it to the camera's real position the camera drifts away.
// Follow: ease the camera toward the player
const goalX = player.x - screenW / 2;
camera.x += (goalX - camera.x) * (1 - Math.exp(-follow * dt));
camera.x = Math.max(0, Math.min(camera.x, worldW - screenW));  // stay in the level

// Shake: trauma jumps up on a hit and fades out
trauma = Math.max(0, trauma - dt * 1.5);
const shake = trauma * trauma;                    // squared feels punchier
const ox = (Math.random() * 2 - 1) * maxShake * shake;
const oy = (Math.random() * 2 - 1) * maxShake * shake;

// Draw everything shifted by the camera (plus the shake)
ctx.save();
ctx.translate(-camera.x + ox, -camera.y + oy);
drawWorld(ctx);
ctx.restore();

function onExplosion() { trauma = 1; }
StandardSystems

Timers & Cooldowns

Fire rate, reloading, buffs and spawners are all just numbers that count down with .

The trigger is held automatically. Turn that off, then hold the mouse or Space to fire yourself.

A cooldown is a number of seconds remaining. Every subtract dt (never below zero). When it hits zero the action is ready again. After the action you set it back to its full duration. Fire rate is just 1 ÷ shots per second.

Chain a few timers and you get real weapon systems: a cooldown between shots, a magazine that runs dry, and a reload timer that refills it. Count with dt, not with frames, so rates stay the same on every machine.

Key ideacooldown = max(0, cooldown − dt). After a shot: cooldown = 1 / shotsPerSecond.
Watch outDo not time things by counting frames, such as "wait 30 frames". That is half a second at 60 but a full second at 30 FPS. Count seconds with dt instead.
const fireRate = 6;               // shots per second
const magSize = 12;
const reloadTime = 1.2;           // seconds

let cooldown = 0, ammo = magSize, reloading = 0;

function update(dt) {
  cooldown = Math.max(0, cooldown - dt);           // timers tick down with dt

  if (reloading > 0) {
    reloading -= dt;
    if (reloading <= 0) ammo = magSize;            // reload finished
    return;
  }

  if (fireHeld && cooldown === 0 && ammo > 0) {
    spawnBullet();
    ammo--;
    cooldown = 1 / fireRate;                       // time until the next shot
    if (ammo === 0) reloading = reloadTime;        // empty: start reloading
  }
}
StandardSystems

Particle Systems

Hundreds of tiny short-lived objects create fire, smoke, sparks and explosions. Each one is just , and a lifetime.

Move the emitter with the mouse. Click for an explosion burst.

A particle system is an emitter that keeps spawning small objects. Each particle gets a position, a random velocity within some spread, and a lifetime. Every it moves with gravity applied, ages, and is removed when its life is over.

The look comes from how you change properties over a particle's life: fade the alpha, shrink the size, shift the color from yellow to red. Add a little randomness to and lifetime so no two look alike, and use additive blending for glowing effects. Remove dead particles every frame, or the list grows without limit.

Key ideaSpawn with random velocity. Each frame: vy += gravity·, move, age. Draw using life ÷ maxLife (0→1).
Watch outCap the particle count. A burst of 10,000 on a slow device will tank the .
const particles = [];

function emit(x, y) {
  const a = baseAngle + (Math.random() - 0.5) * spread;     // radians
  const s = speed * (0.5 + Math.random() * 0.5);            // vary the speed
  particles.push({
    x, y,
    vx: Math.cos(a) * s,
    vy: Math.sin(a) * s,
    life: 0,
    maxLife: lifespan * (0.7 + Math.random() * 0.3),
  });
}

function update(dt) {
  for (const p of particles) {
    p.vy += gravity * dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.life += dt;
  }
  // remove the dead ones (keep the array from growing forever)
  for (let i = particles.length - 1; i >= 0; i--) {
    if (particles[i].life >= particles[i].maxLife) particles.splice(i, 1);
  }
}

function draw(ctx) {
  for (const p of particles) {
    const t = p.life / p.maxLife;                // 0 = born, 1 = dead
    ctx.globalAlpha = 1 - t;                     // fade out
    ctx.fillStyle = 'hsl(' + (50 - 50 * t) + ', 100%, 55%)';   // yellow -> red
    ctx.fillRect(p.x, p.y, 6 - 4 * t, 6 - 4 * t);              // shrink
  }
  ctx.globalAlpha = 1;
}
StandardGame feel

Coyote Time & Jump Buffering

Tiny invisible grace periods that make a platformer feel fair. Players think they pressed jump "just in time", so let them.

Both jumps fail at first. Raise the grace windows above the press delays and watch them succeed.

Coyote time (named after the cartoon coyote who hovers after running off a cliff) lets the player jump for a split second after leaving a ledge. Keep a timer that is full while you stand on the ground and counts down when you don't; if it is above zero, a jump is allowed.

Jump buffering is the mirror image. If the player presses jump a few before landing, remember that press for a moment and perform the jump the instant they touch the ground. Both windows are only about 0.08 to 0.15 seconds. They are invisible but they remove the "I pressed it, why didn't it jump?" feeling.

Key ideaJump if (bufferTimer > 0 AND coyoteTimer > 0). Reset both to 0 after jumping so you can't double jump.
const COYOTE = 0.10;   // seconds you can still jump after leaving a ledge
const BUFFER = 0.10;   // seconds a too-early jump press is remembered

let coyoteTimer = 0;
let bufferTimer = 0;

function update(dt) {
  // Coyote: full while grounded, counting down once airborne
  coyoteTimer = player.onGround ? COYOTE : coyoteTimer - dt;

  // Buffer: refill whenever jump is pressed, otherwise count down
  bufferTimer = jumpPressed ? BUFFER : bufferTimer - dt;

  if (bufferTimer > 0 && coyoteTimer > 0) {
    player.vy = -jumpSpeed;
    bufferTimer = 0;          // consume both so we can't double jump
    coyoteTimer = 0;
  }
}

Advanced

Physics simulation, optimization and AI: springs, orbits, ropes, SAT, flocking and pathfinding.

AdvancedPhysics

Elastic Collisions & Momentum

Make circles bounce off each other realistically. Heavy balls push light ones around, and is conserved.

Click to blast the balls away from the cursor. Big balls are heavier (mass = radius²).

When two balls collide, only the part of their along the line between their centers (the ) changes. The sideways part is untouched. Work out how fast they approach each other along the normal, then apply an of equal size and opposite direction to each ball.

decides who moves more: the impulse is divided by each ball's mass, so a heavy ball barely changes while a light one is flung away. With 1 the collision is perfectly and is preserved. Always push overlapping balls apart as well, or they may stay stuck inside each other.

Key ideaapproach = (vA − vB) · n. j = (1 + e) · approach / (1/mA + 1/mB). vA −= (j/mA)·n, vB += (j/mB)·n.
Watch outOnly apply the impulse while the balls are still moving toward each other (approach > 0). If they are already separating, skip it, or they get glued together.
function collide(a, b, restitution) {
  const dx = b.x - a.x, dy = b.y - a.y;
  const dist = Math.hypot(dx, dy);
  if (dist === 0 || dist >= a.r + b.r) return;       // not touching

  const nx = dx / dist, ny = dy / dist;              // collision normal (A -> B)

  // how fast A approaches B along the normal
  const approach = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny;
  if (approach > 0) {                                // only if moving together
    const j = ((1 + restitution) * approach) / (1 / a.m + 1 / b.m);
    a.vx -= (j / a.m) * nx;  a.vy -= (j / a.m) * ny;
    b.vx += (j / b.m) * nx;  b.vy += (j / b.m) * ny;
  }

  // push them apart so they don't stay overlapped (heavier moves less)
  const overlap = a.r + b.r - dist;
  const total = 1 / a.m + 1 / b.m;
  a.x -= nx * overlap * (1 / a.m) / total;  a.y -= ny * overlap * (1 / a.m) / total;
  b.x += nx * overlap * (1 / b.m) / total;  b.y += ny * overlap * (1 / b.m) / total;
}
AdvancedPhysics

Springs & Damping

: the further a spring is stretched, the harder it pulls back. Add and you get wobble that settles.

Grab the weight with the mouse and let go. Try damping 0, then raise it.

A spring pulls an object back toward its rest position with a to how far it is stretched: F = −k × stretch. A spring (bigger k) snaps back faster. On its own, though, it would bounce forever.

Damping adds a second force that opposes the : F = −c × v. Too little and the object wobbles for ages; too much and it creeps back sluggishly. Somewhere in between is the sweet spot used for wobbly UI, jelly characters, camera recoil and suspension. Divide the total force by to get , then as usual.

Key ideaforce = −k·stretch − c·velocity. acceleration = force / mass.
Watch outStiff springs with large time steps explode. Split the into several smaller steps () to keep them stable.
const k = 25;            // stiffness: how hard it pulls back
const damping = 1.0;     // how much motion is resisted
const mass = 1;

function update(dt) {
  // several small steps are much more stable than one big one
  const steps = 8, h = dt / steps;
  for (let i = 0; i < steps; i++) {
    const stretch = bob.y - (anchor.y + restLength);      // distance from rest
    const force = -k * stretch - damping * bob.vy         // Hooke + damping
                + mass * gravity;
    bob.vy += (force / mass) * h;
    bob.y  += bob.vy * h;
  }
}
AdvancedPhysics

Pendulum

Swinging rope, wrecking balls and clock hands: store an angle instead of x/y and let accelerate the angle.

Drag the bob to a new angle and release.

Position isn't the natural way to describe a swing. A pendulum is better described by one number, its angle from straight down. Gravity pulls hardest when the arm is horizontal and not at all when it is vertical, which gives = −(g ÷ length) × (angle).

the angular acceleration into angular velocity, and that into the angle, exactly like linear motion. Convert to x and y with sine and cosine only for drawing. A longer arm swings slower, and stronger gravity swings faster. The period is about 2π × √(length ÷ g), for small swings.

Key ideaα = −(g / L)·sin(θ). ω += α·. θ += ω·dt. Then x = pivot.x + L·sin(θ), y = pivot.y + L·cos(θ).
Watch outKeep angles in . Mixing degrees into sin/cos produces nonsense.
const pivot = { x: 200, y: 50 };
let angle = 1.2;               // radians from straight down
let angularVel = 0;

function update(dt) {
  // gravity pulls hardest when the arm is horizontal (sin = 1)
  const angularAccel = -(gravity / length) * Math.sin(angle)
                       - damping * angularVel;
  angularVel += angularAccel * dt;
  angle += angularVel * dt;
}

// Only convert to x/y when you need to draw it
const bob = {
  x: pivot.x + Math.sin(angle) * length,
  y: pivot.y + Math.cos(angle) * length,
};
AdvancedPhysics

Orbital Gravity

Newton's : pull toward a star gets weaker with distance. Sideways turns falling into orbiting.

Click anywhere to launch a planet. Its starting speed is "circular speed × orbit shape".

between two bodies pulls with a to 1 ÷ distance². Compute the from the planet to the star, it, and accelerate the planet along it. That is all the physics there is.

Orbits appear on their own from speed. If the planet moves sideways fast enough it keeps "missing" the star (a circle: v = √(μ ÷ r)). A little slower or a little faster and the orbit stretches into an . Much slower and the planet falls into the star. At about 1.4 times the circular speed (the escape speed) it flies away for good. Use small time steps and a minimum distance (softening), because the pull becomes huge very close to the star.

Key idea = μ / r² toward the star. Circular orbit speed: v = √(μ / r), to the pull.
Watch outThe simplest form of (move the position first, using the old ) slowly adds energy, so orbits spiral outward. Updating the velocity first, as this demo does, and taking small steps () keeps orbits stable.
const star = { x: 320, y: 180 };
const mu = 1000000;                  // G * starMass: how strong the pull is

function update(dt) {
  const steps = 8, h = dt / steps;   // small steps keep orbits stable
  for (let i = 0; i < steps; i++) {
    for (const p of planets) {
      const dx = star.x - p.x, dy = star.y - p.y;
      const distSq = Math.max(dx * dx + dy * dy, 400);   // soften close passes
      const dist = Math.sqrt(distSq);
      const accel = mu / distSq;                         // inverse-square law
      p.vx += (dx / dist) * accel * h;
      p.vy += (dy / dist) * accel * h;
      p.x += p.vx * h;
      p.y += p.vy * h;
    }
  }
}

// Launch into a circular orbit at distance r (velocity sideways to the pull)
function circularVelocity(p) {
  const dx = p.x - star.x, dy = p.y - star.y;
  const r = Math.hypot(dx, dy);
  const speed = Math.sqrt(mu / r);
  return { vx: (-dy / r) * speed, vy: (dx / r) * speed };
}
AdvancedPhysics

Verlet Integration & Ropes

Store where a point is and where it was. is implied. Connect points with distance constraints to make ropes and cloth.

The top end follows the mouse. Set iterations to 1 to see a stretchy, rubbery rope.

keeps two positions per point: current and previous. The difference between them is the velocity, so you never store it. To step, move the point by that difference, then add . The big win: if you move a point (to fix a constraint or collision) its velocity changes automatically.

A rope is a chain of points where each neighboring pair wants to stay one "rest length" apart. After each Verlet step, loop over the links and nudge both ends toward the correct distance. A single pass is stretchy like rubber; repeating the pass several times (iterations) makes the rope stiff. The same idea builds cloth, soft bodies and ragdolls.

Key ideanext = current + (current − previous) + gravity·². Then repeat: pull each linked pair back to restLength.
Watch outMore iterations = but costlier. Ropes with a heavy weight on the end need many more iterations than a plain chain. Verlet also needs a fixed time step (this demo uses 1/120 s), because the velocity is implied by how far a point moved in one step. Changing the step size changes the .
// each point stores where it is and where it was last step
const points = [];                       // { x, y, px, py, pinned }

function step(h) {                       // h = fixed time step, e.g. 1/120 s
  // 1) Verlet: velocity is simply (current - previous)
  for (const p of points) {
    if (p.pinned) continue;
    const vx = (p.x - p.px) * 0.995;     // tiny bit of air drag
    const vy = (p.y - p.py) * 0.995;
    p.px = p.x;  p.py = p.y;
    p.x += vx;
    p.y += vy + gravity * h * h;
  }

  // 2) Constraints: pull linked points back to restLength.
  //    More iterations = a stiffer rope.
  for (let i = 0; i < iterations; i++) {
    for (const [a, b] of links) {
      const dx = b.x - a.x, dy = b.y - a.y;
      const dist = Math.hypot(dx, dy) || 0.0001;
      const diff = (dist - restLength) / dist;
      const wa = a.pinned ? 0 : 1, wb = b.pinned ? 0 : 1;
      const total = wa + wb;
      if (total === 0) continue;
      a.x += dx * diff * (wa / total);  a.y += dy * diff * (wa / total);
      b.x -= dx * diff * (wb / total);  b.y -= dy * diff * (wb / total);
    }
  }
}
AdvancedCollision

Rotated Shapes (SAT)

The detects collisions between any shapes, including rotated boxes, and tells you how to push them apart.

Move the mouse to drag the box. The thick bars are the two shapes' shadows on the tightest axis.

Boxes that rotate can't use the simple test. SAT says: two convex shapes do NOT overlap if you can find a line (an axis) such that, when both shapes are squashed () onto it, their shadows don't overlap. You only need to test the axes to each edge of both shapes.

If every axis shows overlapping shadows, the shapes collide. And the axis with the smallest overlap is a gift: move one shape along that axis by that amount (the , MTV) and they are separated by the shortest possible distance. That is the response for sliding off slopes and other tilted surfaces.

Key ideaFor each edge normal: project both shapes onto it. A gap on ANY axis = no collision. Otherwise push out along the smallest overlap.
Watch outSAT only works for convex shapes. Split concave ones (like an L or a star) into convex pieces first.
function project(poly, axis) {
  let min = Infinity, max = -Infinity;
  for (const p of poly) {
    const d = p.x * axis.x + p.y * axis.y;       // dot product = shadow position
    min = Math.min(min, d);
    max = Math.max(max, d);
  }
  return { min, max };
}

function satCollide(a, b) {
  let depth = Infinity, axisOut = null;
  for (const poly of [a, b]) {
    for (let i = 0; i < poly.length; i++) {
      const p1 = poly[i], p2 = poly[(i + 1) % poly.length];

      // the edge's normal is the axis to test
      let axis = { x: -(p2.y - p1.y), y: p2.x - p1.x };
      const len = Math.hypot(axis.x, axis.y);
      axis = { x: axis.x / len, y: axis.y / len };

      const pa = project(a, axis), pb = project(b, axis);
      const overlap = Math.min(pa.max, pb.max) - Math.max(pa.min, pb.min);
      if (overlap <= 0) return null;             // a gap: NOT colliding

      if (overlap < depth) { depth = overlap; axisOut = axis; }
    }
  }
  return { depth, axis: axisOut };               // push by axis * depth
}
AdvancedCollision

Spatial Grid (Broad-Phase)

Checking every object against every other one gets slow fast. A grid lets each object only look at its neighbors.

Crank up the object count, then toggle the grid off to watch the check count explode.

With n objects there are n × (n − 1) ÷ 2 pairs. Ten objects need 45 checks, but a thousand need almost 500,000 per . Most of those pairs are nowhere near each other, so the checks are wasted.

A spatial grid splits the world into cells. Each frame, drop every object into the cell its center is in. Objects can only collide with others in the same cell or the next cells over, so you run the precise () test just on those. Cheap broad phase first, accurate narrow phase second: that is how most physics engines work. Keep cells at least as large as your biggest object.

Key ideacell = (floor(x / size), floor(y / size)). Only test pairs in the same or adjacent cells.
Watch outRebuild (clear and refill) the grid every frame for moving objects. And pick a cell size near the size of a typical object: too small or too large wastes time.
const cellSize = 40;                       // >= the biggest object's diameter
const cols = Math.ceil(width / cellSize);
const rows = Math.ceil(height / cellSize);

function findCollisions(objects) {
  // 1) Broad phase: bucket every object into a grid cell
  const grid = Array.from({ length: cols * rows }, () => []);
  for (const o of objects) {
    const cx = Math.min(cols - 1, Math.max(0, Math.floor(o.x / cellSize)));
    const cy = Math.min(rows - 1, Math.max(0, Math.floor(o.y / cellSize)));
    grid[cx + cy * cols].push(o);
  }

  // 2) Narrow phase: only test objects in the same / neighboring cells
  const around = [[0, 0], [1, 0], [-1, 1], [0, 1], [1, 1]];   // each pair seen once
  for (let cy = 0; cy < rows; cy++) {
    for (let cx = 0; cx < cols; cx++) {
      const here = grid[cx + cy * cols];
      for (const [ox, oy] of around) {
        const nx = cx + ox, ny = cy + oy;
        if (nx < 0 || nx >= cols || ny >= rows) continue;
        const there = grid[nx + ny * cols];
        for (let i = 0; i < here.length; i++) {
          for (let j = (ox === 0 && oy === 0 ? i + 1 : 0); j < there.length; j++) {
            if (circlesOverlap(here[i], there[j])) onHit(here[i], there[j]);
          }
        }
      }
    }
  }
}
AdvancedAI

Steering Behaviors

Make enemies seek, flee, arrive and intercept by steering their instead of teleporting them. Smooth, natural-looking AI.

The pink dot is the target (move the mouse). Yellow = desired velocity, pink = steering force.

Instead of moving an AI straight to the target, give it a desired velocity (the direction and it would like to have) and compare it to its current velocity. The difference is a steering . Limit that force and apply it, so the agent turns smoothly, overshoots a little, and feels alive.

Different goals just change the desired velocity. Seek aims at the target; flee aims away; arrive scales the speed down inside a slowing radius so it stops gently; pursue aims at where a moving target is going to be, using its velocity to predict a future position. Combine several (plus obstacle avoidance) and you have the core of most game AI movement.

Key ideasteering = (desiredVelocity − velocity, maxForce). velocity += steering·.
Watch outSeek has no brakes: it always wants full speed, so near the target the agent overshoots and jitters back and forth (or loops around it when its steering force is weak). Use arrive for anything that should come to a halt.
function steer(agent, desired, maxForce, dt) {
  // steering = what we want - what we have, with a limited force
  let sx = desired.x - agent.vx;
  let sy = desired.y - agent.vy;
  const len = Math.hypot(sx, sy);
  if (len > maxForce) { sx = (sx / len) * maxForce; sy = (sy / len) * maxForce; }

  agent.vx += sx * dt;
  agent.vy += sy * dt;
}

function toward(from, to, speed) {
  const dx = to.x - from.x, dy = to.y - from.y;
  const d = Math.hypot(dx, dy) || 1;
  return { x: (dx / d) * speed, y: (dy / d) * speed, dist: d };
}

// Each behavior just answers: "what velocity would I like to have?"
const seek = (agent, target, maxSpeed) => {
  const d = toward(agent, target, maxSpeed);
  return { x: d.x, y: d.y };
};
const flee = (agent, target, maxSpeed) => {
  const d = seek(agent, target, maxSpeed);
  return { x: -d.x, y: -d.y };                      // the same, reversed
};
const arrive = (agent, target, maxSpeed, slowRadius) => {
  const d = toward(agent, target, maxSpeed);
  const slow = Math.min(1, d.dist / slowRadius);    // 1 far away, 0 at the target
  return { x: d.x * slow, y: d.y * slow };
};
const pursue = (agent, target, maxSpeed) => {
  const lookAhead = toward(agent, target, maxSpeed).dist / maxSpeed;   // seconds to get there
  const future = { x: target.x + target.vx * lookAhead,                // where it will be
                   y: target.y + target.vy * lookAhead };
  return seek(agent, future, maxSpeed);
};

// Each frame: pick one, then steer toward it
steer(agent, arrive(agent, target, maxSpeed, 110), maxForce, dt);
AdvancedAI

Flocking (Boids)

Three tiny rules (stay apart, line up, stay together) make groups of agents move like birds and fish.

Move the mouse through the flock: it acts like a predator. Drag the weights to change the personality.

Each boid only looks at neighbors inside its vision radius and follows three rules. Separation: steer away from anyone too close. Alignment: steer toward the average heading of neighbors. Cohesion: steer toward the average position of neighbors. Nobody is in charge, yet the flock moves as one.

Every rule produces a steering , and you add them up with weights. Tuning the weights changes the personality: more separation gives loose swarms, more cohesion tight balls. Add a fourth force, like fleeing from the player's cursor, and you get dynamic crowds, schools, bats and bullet-hell patterns.

Key ideasteer = sep·wS + align·wA + cohesion·wC, each limited to maxForce. Look only at nearby boids.
Watch outChecking every boid against every other is . For large flocks use a spatial grid (see Spatial Grid) to find neighbors.
function flock(boids, dt) {
  for (const b of boids) {
    const sep = { x: 0, y: 0 }, ali = { x: 0, y: 0 }, coh = { x: 0, y: 0 };
    let n = 0;

    for (const o of boids) {
      if (o === b) continue;
      const dx = o.x - b.x, dy = o.y - b.y;
      const d = Math.hypot(dx, dy);
      if (d > vision) continue;                  // only look at close neighbors
      n++;
      ali.x += o.vx;  ali.y += o.vy;             // alignment: their heading
      coh.x += o.x;   coh.y += o.y;              // cohesion: their position
      if (d < vision * 0.4) {                    // separation: too close, back off
        sep.x -= dx / (d * d);
        sep.y -= dy / (d * d);
      }
    }

    if (n > 0) {
      const a = steerToward(b, ali.x / n, ali.y / n);            // match heading
      const c = steerToward(b, coh.x / n - b.x, coh.y / n - b.y); // move to center
      const s = steerToward(b, sep.x, sep.y);                    // spread out
      b.vx += (s.x * wSep + a.x * wAli + c.x * wCoh) * dt;
      b.vy += (s.y * wSep + a.y * wAli + c.y * wCoh) * dt;
    }
    limitSpeed(b, maxSpeed);
  }
  for (const b of boids) { b.x += b.vx * dt; b.y += b.vy * dt; wrapAround(b); }
}

// steerToward = scale (dx,dy) to maxSpeed, subtract current velocity,
// then clamp to maxForce (see Steering Behaviors).
AdvancedAI

A* Pathfinding

Find the shortest path through a maze. A* explores the most promising squares first, guided by a guess of the distance left.

Click and drag to draw or erase walls. Drag the green start or pink goal square to move them.
  • Start
  • Goal
  • Open list (waiting)
  • Closed list (explored)
  • Final path
  • Wall

Put the map on a grid. Each open square is a , and neighboring squares you can step between are connected. Keep an "" of squares waiting to be explored and a "" of squares you have already explored. Always expand the open square with the lowest f = g + h, where g is the known cost from the start and h is a guess of the cost still left to the goal. When you reach the goal, follow the "came from" links backwards to rebuild the path.

The heuristic is what makes A* fast. With h = 0 it degrades into and floods the whole map evenly. A good guess (like on a 4-direction grid) pulls the search straight toward the goal. It must never overestimate, or the path may not be the shortest. If you allow diagonal moves, Manhattan distance can overestimate (a diagonal step covers two blocks for the price of about 1.4), so use Euclidean there.

Try it in the demo: yellow squares are the open list, cyan squares are the closed list, and the green line is the finished path. Switch the heuristic to "None (Dijkstra)" and watch how many more squares get explored before the goal is found.

Key ideaf = g + h. Always expand the open node with the lowest f. g = cost so far, h = estimated cost to the goal.
Watch outUse a (binary heap) instead of scanning the whole open list for large maps. And don't re-run it every : cache paths and recompute when the map changes.
function astar(start, goal, isWall) {
  const key = (n) => n.x + ',' + n.y;
  const h = (n) => Math.abs(n.x - goal.x) + Math.abs(n.y - goal.y);   // Manhattan

  const open = [start];                          // nodes waiting to be explored
  const g = new Map([[key(start), 0]]);          // cheapest known cost from start
  const cameFrom = new Map();

  while (open.length > 0) {
    // take the node with the lowest f = g + h
    open.sort((a, b) => g.get(key(a)) + h(a) - (g.get(key(b)) + h(b)));
    const cur = open.shift();

    if (cur.x === goal.x && cur.y === goal.y) {  // reached the goal: walk back
      const path = [cur];
      while (cameFrom.has(key(path[0]))) path.unshift(cameFrom.get(key(path[0])));
      return path;
    }

    for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
      const next = { x: cur.x + dx, y: cur.y + dy };
      if (isWall(next)) continue;
      const cost = g.get(key(cur)) + 1;
      if (cost < (g.get(key(next)) ?? Infinity)) {   // found a cheaper way here
        g.set(key(next), cost);
        cameFrom.set(key(next), cur);
        if (!open.some((o) => key(o) === key(next))) open.push(next);
      }
    }
  }
  return null;                                   // no path exists
}

Math & terms, in plain English

Never studied trigonometry or calculus? You do not need to. Here is every word that shows up with a dotted underline above, explained without the textbook.

Browse all 70 terms
AABB / hitbox
An invisible rectangle around an object whose sides line up with the screen edges (it never tilts). Overlap tests for them are very cheap, so games use them as hitboxes.
Acceleration
How quickly velocity changes. A car going from 0 to 60 mph is accelerating; one cruising steadily is not.In games: Measured in "pixels per second, per second".
Algorithm
A step-by-step recipe a computer follows to solve a problem.
Angular velocity
Spin speed: how fast an angle is changing, like the speed of a turning wheel. Angular acceleration is how fast that spin speed changes.
atan2
The reverse of sine and cosine. Give it "how far across" and "how far down" and it tells you the angle that points that way.angle = atan2(dy, dx)In games: How a turret works out which way to face its target.
Broad phase / narrow phase
Collision checking in two passes. A cheap first pass rules out things that are obviously far apart (broad), then careful checks run only on the few that might really touch (narrow).
Calculus
The math of change (how fast things are changing) and accumulation (adding up lots of tiny changes). You do not need it to build games: games turn its ideas into simple "add a little each frame" steps.
Clamp
Squeeze a number into a range. Clamping 15 to the range 0 to 10 gives 10; clamping −3 gives 0; clamping 7 leaves it at 7.In games: Keeps speeds, health and positions from going past their limits.
Closed list
In pathfinding: the squares you have already explored, so you never waste time on them twice.
Convex
A shape with no dents. Any straight line drawn between two points inside it stays inside. Squares, triangles and hexagons are convex; a crescent or a star is not.
Damping
Gradually removing energy from a wobble so it settles. With no damping something bounces forever; with a lot it creeps back slowly.
Delta time (dt)
The tiny slice of time, in seconds, that passed since the last frame. At 60 frames per second it is about 0.0167 seconds.distance this frame = speed × dtIn games: Multiply any speed by it and things travel the same distance per second on every computer, fast or slow.
Denominator / divide by zero
The denominator is the bottom number of a fraction. Dividing by zero has no answer: the computer gives back infinity or NaN and anything that touches it breaks.In games: Always check that the number you are dividing by is not zero.
Derivative
A calculus word for "how fast something is changing right now". Think of a car speedometer: it shows the derivative of your position. Velocity is the derivative of position, and acceleration is the derivative of velocity.In games: You almost never calculate derivatives yourself. Games just keep track of the results: velocity and acceleration.
Dijkstra's algorithm
A pathfinding method that always explores the cheapest route found so far, spreading out evenly in every direction. A* is Dijkstra plus a guess about where the goal is.
Dot product
Multiply two arrows' matching parts and add them up. The answer says how much they point the same way: large and positive is the same way, zero is at right angles, negative is opposite.In games: Used for "is that enemy in front of me?" and for measuring how fast two things are closing in.
Drag
Resistance from moving through air or water. The faster you go, the harder it pushes back.
Easing
Reshaping a movement so it speeds up or slows down smoothly instead of moving at a constant rate. Ease-out slows to a gentle stop; ease-in starts gently.
Elastic collision
A collision where the total movement energy (kinetic energy) is the same before and after, with nothing lost to heat, sound or dents. Two billiard balls come close.
Ellipse
A stretched circle, like an oval. Planets travel around stars on ellipses.
Euler method
The simplest way to move a simulation forward: add acceleration × dt to velocity, and velocity × dt to position. "Semi-implicit" just means you update the velocity first, which behaves much more stably.
exp (exponential)
A curve where something shrinks or grows by the same percentage every moment. exp(−k × dt) is how games say "lose the same percentage of the speed each second", and it works at any frame rate.e^(−x), where e is about 2.718
Force
A push or pull. The bigger the force on the same object, the faster it speeds up.force = mass × acceleration
Frame
One single picture in the animation. A game draws dozens of these every second, the same way a flip-book shows many pages quickly.
Frame rate (FPS)
How many pictures (frames) the game draws each second. 60 FPS means 60 pictures per second. Faster computers can reach higher numbers.In games: It differs from player to player, so your game logic should never assume a particular frame rate.
Frame-rate independent
Behaves the same no matter how many frames per second the game runs at. You get there by scaling every change by delta time.
Friction
The rubbing that slows sliding things down. A hockey puck on ice has very little; on carpet it has a lot.
Gravity
A steady pull toward the ground (or toward a planet).In games: In a platformer it is just a number added to the downward velocity every frame.
Heuristic
An educated guess that speeds up a search. In pathfinding it is a quick estimate of how far is left to the goal.
Hooke's law
The more you stretch or squash a spring, the harder it pulls back, in exact proportion. Double the stretch, double the pull.force = −stiffness × stretch
Hz (hertz)
Times per second. A 144 Hz screen refreshes 144 times every second.
Impulse
A sudden push that changes velocity instantly, like a bat hitting a ball.
Integration
Adding up many tiny changes over time to get the total. Each frame you add a little velocity to the position, and after many frames those small additions build the whole path. Calculus calls this an integral.In games: Every game that moves things frame by frame is doing integration, even if nobody says the word.
Inverse-square law
A pattern where an effect weakens quickly with distance: twice as far means one quarter as strong, three times as far means one ninth.pull = strength ÷ distance²In games: Gravity and light both follow it.
Kinetic energy
The energy an object has because it is moving. Bouncy collisions keep it; sticky ones turn some of it into heat.½ × mass × speed²
Lerp
Short for "linear interpolation": slide part of the way from A to B. lerp(0, 100, 0.25) gives 25. A fraction of 0 gives A, 1 gives B, and 0.5 gives the midpoint.lerp(a, b, t) = a + (b − a) × t
Line segment
A straight line with a start and an end, unlike a true line that goes on forever.
Magnitude
The length of a vector: how big the arrow is, ignoring which way it points.length of (x, y) = √(x² + y²)
Manhattan distance
Distance counted only with horizontal and vertical steps, like walking city blocks with no diagonal shortcuts.|dx| + |dy|
Mass
How much "stuff" an object has, and so how hard it is to push. A heavy object speeds up less than a light one for the same push.
Minimum translation vector
The shortest push that would separate two overlapping shapes: which way to push, and how far.
Momentum
Mass × velocity: how hard something is to stop. A truck and a bicycle moving at the same speed have very different momentum.momentum = mass × velocityIn games: In a collision the total momentum is shared between the objects, not lost.
NaN
"Not a Number": what code gives you for impossible math like 0 ÷ 0. It spreads: anything calculated with NaN becomes NaN too, and objects can vanish from the screen.
Node & graph
A node is a spot on a map you can stand on, like one square of a grid. Nodes plus the connections between them are called a graph, which is the picture a pathfinding algorithm works with.
Normal
An arrow of length 1 pointing straight out of a surface, at a right angle to it. The "collision normal" says which way things should bounce or be pushed apart.
Normalize
Resize an arrow so its length is exactly 1 while keeping its direction. What is left is a pure "which way", with no "how much".normalized = (x, y) ÷ lengthIn games: Multiply the result by the speed you want and every direction moves at exactly that speed.
O(n²) (Big-O)
A shorthand for how fast the work grows. O(n²) means that doubling the number of objects makes the work four times bigger, which gets slow very quickly.
Open list
In pathfinding: the squares you have discovered but not explored yet, like a to-do list. Each turn you pick the most promising one.
Parabola
The smooth arch a thrown ball traces: steady sideways speed plus steady gravity pulling it down.
Parallel
Running side by side in the same direction and never meeting, like train tracks.
Perpendicular
At a right angle (90°) to something, like the corner of a sheet of paper.
Pixel
One tiny dot on the screen. Positions and sizes in 2D games are usually measured in pixels.
Priority queue
A to-do list that always hands you the most urgent item first, without re-sorting everything each time.
Projection
Squashing a shape flat onto a line, like the shadow it would cast on a wall. Comparing shadows is how the separating axis test works.
Proportional
Rising and falling together at the same rate. If A is proportional to B, doubling B doubles A.
Pythagorean theorem
In a right-angled triangle, the two short sides, each multiplied by itself and added together, equal the long side multiplied by itself. It is how you measure the straight-line distance between two points.a² + b² = c²In games: Any time you need "how far apart are these two things?", this is what runs underneath.
Radians
An angle unit that code prefers over degrees. A full turn is 2π (about 6.28) instead of 360°, and a half turn is π (about 3.14).radians = degrees × π ÷ 180
Restitution
Bounciness. A number from 0 to 1 for the fraction of its speed an object keeps after a bounce: 1 is a perfect super-ball, 0 is a lump of clay.
Separating Axis Theorem
A rule for testing whether two convex shapes touch: if you can find any line where their shadows do not overlap, the shapes are apart.
Sine & cosine
Give them an angle and they tell you how far across (cosine) and how far up or down (sine) you would end up after one step in that direction.vx = cos(angle) × speed, vy = sin(angle) × speedIn games: Multiply by a speed to turn an angle into a velocity. Plotted over time they also draw smooth waves, handy for bobbing and swaying.
Speed
How fast something moves, ignoring direction.
Sprite
A 2D picture that represents a character or object on screen.
Square root
The number that gives you the original when multiplied by itself. The square root of 9 is 3, and of 25 is 5.In games: Distance formulas use it. It is slower for a computer than plain arithmetic, so games skip it when they can.
Squared
Multiplied by itself: 4 squared is 4 × 4 = 16, written 4². Squaring a number between 0 and 1 makes it smaller (0.5 squared is 0.25).In games: Comparing squared distances avoids the slower square root. Squaring also makes an effect ramp up gently, then hit hard near the top.
Stiffness
How strong a spring is. A high number snaps back fast; a low number is soft and floppy.
Substeps
Splitting one frame into several smaller updates, like taking ten small steps instead of one big leap. It stops fast or springy things from going wrong.
Trigonometry
The math of angles and triangles. In games it converts between "an angle" and "a direction", for example turning "point 30 degrees" into "move this far across and this far down".
Vector
An arrow: a direction plus a length. It is written as a pair of numbers, like (3, 4), meaning "3 across and 4 down".In games: Positions, velocities, pushes and aiming directions are all stored as vectors.
Velocity
How fast something moves and in which direction, like "200 pixels per second to the right".In games: Speed is the same idea without the direction.
Verlet
A way of moving points that remembers where each point was last frame. The difference between "now" and "before" is the velocity, so you never store it. Great for ropes and cloth.