Tutorial
-
BFS — Breadth-First Search
Time to give your characters some serious brains! So far, your hero has been pretty… let’s say “directionally challenged.” Tell them to go left, they go left - even straight into a wall! But what if they could think for themselves and find clever paths around obstacles?
Welcome to the world of pathfinding - the AI magic behind every smart enemy in RTS games, every helpful companion in RPGs, and every tower defense unit that knows exactly how to reach their target. You’re about to implement the same algorithms that power characters in Starcraft, Age of Empires, and countless other games!
-
Mouse to Move
Put down the keyboard and click anywhere on the map. The hero walks there. Click-to-move is the movement style behind countless RPGs, strategy games, and point-and-click adventures. Let’s build it!
Loading editor…Notice the hero steps from tile center to tile center - no stopping halfway. That’s the key characteristic of tile-based movement: the hero is always perfectly aligned to the grid.
-
Jumping
This tutorial switches from top-down to side-scrolling view. The hero moves left and right with arrow keys and jumps with spacebar. The jump mechanic is built on two properties: an initial upward velocity and a per-frame gravity that pulls the hero back down.
Loading editor…Jump Physics: Making It Feel Right
In this coordinate system, moving up means decreasing Y. Pressing spacebar sets
velocityYto a negative value like-15pixels per frame. Each frame after that, gravity incrementsvelocityYback toward positive (downward): -
Why Tiles?
Games like Super Mario Bros, The Legend of Zelda, and Stardew Valley build their worlds from tiles — small, reusable images arranged on a grid. The technique has been around since the early arcade era, and it’s still standard practice because it solves a real problem efficiently.
So if you want to put a nice background into your game, but the picture would be too large and make the game very slow. What to do? Slice the picture into tiles!
-
Dijkstra's — Terrain Costs
What if your hero doesn’t just want the shortest path — they want the cheapest one? A battlefield isn’t all flat floors. There’s mud that slows you down, roads that speed you up, rivers you’d rather not wade through. Breadth-First Search treats every tile the same. Dijkstra’s algorithm knows better.
Edsger Dijkstra published this algorithm in 1959 — originally to find the shortest driving route between two Dutch cities. Six decades later, it’s still powering pathfinding in games from Civilization to Dwarf Fortress to your next project.
-
Isometric View
Tilt your world 45 degrees and you get the iconic look behind Pokémon, Age of Empires, and Diablo. Isometric view makes a flat tile grid feel like a real 3D space. Best of all, it’s just two lines of math on top of everything you’ve already built:
Loading editor…Walk north of the pillar - it covers you. Walk south - you cover it. All game logic (movement, collision) runs in the flat world grid. Only the final render step converts to the diamond view.
-
Clouds
Cloud platforms are one-way surfaces: the player can jump through them from below, pass through them from the sides, but lands on top when falling. This tutorial adds that behaviour to the jumping system from the previous tutorial.
Loading editor…How Cloud Platforms Work
A solid tile blocks movement from every direction. A cloud tile applies collision only when the player is falling downward: the player can jump through from below, pass through from the sides, but lands on top when descending.
-
Map Format
Maps in tile-based games are stored as 2D arrays — grids of numbers where each value identifies a tile type. The position of each number in the array corresponds directly to its position in the world.
2D arrays
A 2D array is an array whose elements are themselves arrays. Each inner array is a row, and the outer array holds all the rows. Starting simple:
A basic array might store your player’s inventory:
-
Greedy Best-First
Ready to supercharge your AI? While breadth-first search guarantees the shortest path, it can be painfully slow on large maps - exploring EVERYWHERE before finding the target. What if your AI could be smarter and guess which direction to search first?
Enter Best-First Search - the algorithm that adds intuition to pathfinding! Instead of blindly searching in all directions, your AI will make educated guesses about where the target might be, dramatically speeding up path discovery.
-
Isometric Mouse
You know how to move in isometric. You know how to click-to-move. Now combine them. The tricky part isn’t the movement — it’s figuring out which diamond tile the mouse is actually over:
Loading editor…THE CHALLENGE 🤔
In the previous mouse tutorial, converting a click to a tile was simple division:
-
Ladders
Ladders let the player climb vertically through the level using the up and down arrow keys. While climbing, gravity is disabled and the player snaps to the ladder’s centre column. This tutorial adds that system on top of the jumping mechanics from the previous tutorials.
Loading editor…Ladder Types
There are four common ladder variants, and the choice affects level design possibilities:
-
More Maps
2D arrays work well for most tile-based games, but the format has trade-offs. Different game structures call for different storage strategies — this section covers the main options and when each makes sense.
Frame-based mapping
Each number in the array directly represents a sprite frame or tile type. No separate type definitions required — the number is the tile identity.
// Each number = a different tile graphic const levelMap = [ [5, 5, 5, 5, 5], // Stone walls [5, 1, 2, 3, 5], // Floor, grass, water, sand [5, 5, 5, 5, 5] // Stone walls ]; // Define tile ranges for collision const TileRanges = { walkable: [1, 2, 3], // Frames 1-3 are walkable walls: [5], // Frame 5 blocks movement water: [2], // Frame 2 is water (maybe slows player?) damage: [10, 11, 12] // Frames 10-12 hurt the player };Good for: Retro platformers, puzzle games, simple RPGs
Trade-off: Fast to implement and reason about; harder to attach complex behaviour to individual tile types later. -
A*
This is the one. Every pathfinding tutorial builds toward this moment. A* (pronounced “A-star”) is the algorithm used in more shipped games than any other — from Age of Empires to Stardew Valley to AAA blockbusters. It’s optimal like Dijkstra’s and fast like Greedy Best-First, because it’s actually both of them fused together.
The insight is elegant: Dijkstra’s tracks the real cost from start to each tile (
g). Greedy Best-First estimates the remaining cost to the goal (h). A* simply adds them together:f = g + h. Prioritise byf, and you’re guaranteed to find the shortest (or cheapest) path while exploring far fewer tiles than either algorithm alone. -
Isometric Scroll
A 5×5 isometric map is a proof of concept. A real game needs room to breathe. Combine the World Container from the scrolling tutorials with the isometric transform and you get a large diamond world that follows the player:
Loading editor…Notice the diamond shape visible against the dark background at the edges. That’s the one catch with isometric scroll — the viewport is rectangular but the world is diamond-shaped.
-
Moving Tiles
Moving platforms appear in most platformers — the swinging platforms in Donkey Kong Country, the cloud lifts in Mario, the crumbling bridges in Crash Bandicoot. They transform a flat level into a dynamic obstacle that rewards timing. Here’s how to build them.
Loading editor…Before we start coding, let’s agree on the rules. Moving platforms in this tutorial work like cloud tiles - the hero can only land on them from above. Here’s what we need to handle:
-
Rendering a Map
Rendering converts a 2D array into a visual grid. For each value in the map, draw a coloured rectangle at the corresponding pixel position.
Array: Visual result: [1, 1, 1, 1] → 🧱🧱🧱🧱 [1, 0, 0, 1] → 🧱 🌟🌟🧱 [1, 1, 1, 1] → 🧱🧱🧱🧱 Each 1 becomes a solid wall, each 0 becomes walkable space.Loading editor…Map data and tile definitions
The map and tile type definitions from the previous tutorial, ready to use:
-
Bringing it Together
Four algorithms. One demo. Time to put everything together into something that actually feels like a game.
You’re the intruder. You have a 5-second head start before the guard wakes up. The guard uses A* to track your last known position — not your current position, because fair is fair and omniscient guards aren’t fun. Break line of sight, hide in the shadows, and get to the exit before you get caught.
-
Rotate Hero
Ready to make your hero feel more alive? So far our character has been limited to walking in just four directions - up, down, left, and right. That’s fine for a retro RPG, but what if you want to create a top-down shooter, a racing game, or a spaceship adventure? Time to unlock the magic of 360-degree movement!
In this tutorial, you’ll learn how to rotate your hero and move in any direction using the power of trigonometry (don’t worry, it’s easier than it sounds!). By the end, your character will move like they do in games like Asteroids, Hotline Miami, or any twin-stick shooter.
-
Enemy on Platform
A basic wall-bouncing enemy will walk off platform edges and fall. A platform-aware enemy checks for ground ahead before stepping forward and turns back if there is none. This tutorial adds that edge-detection logic to enemy movement.
Loading editor…Random Direction Changes
A
turnChancepercentage applied each frame creates variation between enemy types without adding new AI logic: -
The Hero
The hero is a data object that stores position, size, and a reference to its sprite. Separating data from visuals keeps the game logic independent of how things are drawn.
Loading editor…The hero object
The hero stores two coordinate systems alongside its sprite reference:
-
Going Further
A* will take you a long way. Most shipped tile-based games use it and never need anything else. But pathfinding is a rich field, and knowing what’s beyond the horizon helps you recognise when you’ve outgrown your tools.
This chapter is a map of that territory — less code, more concepts, with enough implementation detail to get you started if you want to explore.
-
Rotate Background
Ready for some serious game magic? In the last tutorial, your hero learned to rotate and move in any direction. Now we’re taking it to the next level: the world itself will rotate around your hero!
This technique creates those mind-bending effects you see in space games like Asteroids, racing games with spinning tracks, or puzzle games where the entire level rotates. Your hero stays perfectly centered while the universe spins around them - it’s like being the center of your own personal tornado!
-
Shoot Him
Projectiles are a common interaction mechanic — the player fires in the direction they last moved, and bullets that reach an enemy remove it from the level. This tutorial adds a bullet system to the side-scrolling platformer from previous tutorials.
Loading editor…Bullet Data Structure
A bullet is a plain object with a position, a velocity, a size, and a sprite. The size matters because collision is AABB (axis-aligned bounding box), not circular distance — two rectangles overlap when neither axis is separated:
-
Keys to Move
Keyboard input in the browser works via two events:
keydownfires when a key is pressed,keyupfires when it’s released. Store the current state of each key in an object, then read that state each frame in the game loop.Loading editor…Character setup
The hero object from the previous tutorial, with direction and movement state added:
-
Bringing it Together
-
Depth
Walk below a pillar and you’re in front of it. Walk above and the pillar covers you. That’s depth - a 2D trick that makes your top-down world feel solid and three-dimensional. Try it:
Loading editor…THE ILLUSION
Top-down games use a simple rule: things lower on the screen are closer to the viewer. Imagine looking down at a scene from above. A character further north (higher up on screen) is physically further away, so objects in the south overlap them.
-
Hit the Wall
Collision detection prevents the hero from entering solid tiles. Before applying a movement, check whether the destination tile is walkable — if it isn’t, cancel the move.
Loading editor…The hero turns light red when a move is blocked and white when it moves freely.
-
Going Further
-
Slopes
Slopes replace the hard tile edges with diagonal surfaces the player slides up and down. The visual is a triangle tile; the physics are a surface height that changes linearly across the tile’s width.
Loading editor…Slope Tile Types
Only two diagonal variants are needed to build any terrain shape:
-
Getting Items
Collectibles are a staple of tile-based games — coins in Mario, rupees in Zelda, rings in Sonic. The pickup system needs to do three things: track what items exist and where, detect when the player steps on one, and remove it permanently so it doesn’t reappear.
Loading editor…Items are different in what they do - coins add a little to your score, gems are worth ten times more. That’s the same trick games use to reward you for exploring off the beaten path. In this tutorial all items just give points, but the same pattern works for health potions, ammo pickups, power-ups, or anything else you want to create!
-
Open the Door
A single room is a demo. A connected world — rooms that lead to other rooms — is a game. This tutorial adds a multi-room system: each room is a map stored in an object, and door tiles trigger transitions between them.
Loading editor…Walk into the yellow door tiles to move between rooms.
-
Locked Doors
A door you can walk through is a transition. A door you have to earn is a puzzle. Locked doors are one of the oldest tricks in game design — find the key, open the way forward. Let’s combine what you know about items and doors to build one.
Loading editor…The gold circle is the key. The red door on the right won’t let you through until you’ve picked it up — then it turns green and you can pass. Try walking into it without the key first.
-
Bringing it Together
Each tutorial in this series introduced one mechanic in isolation. Here they run together: gravity, cloud platforms, moving tiles, enemies with edge detection, projectiles, and a scrolling camera. The goal is not a polished game — it’s a working skeleton that demonstrates how the systems compose without fighting each other.
Loading editor…Controls: arrow keys to move, Space or Up to jump, Shift to shoot.
-
Pushing Tiles
Loading editor…Walk into an orange block and it slides one tile in the direction you were moving — but only if the tile behind it is empty. Walk it into a wall and it stops. Walk it into a corner and it’s stuck there permanently.
-
Scrolling
Your world is bigger than one screen. The camera follows the hero, and the whole world slides past — that’s the technique behind every side-scroller from the original Super Mario Bros to Hollow Knight.
Loading editor…Notice that the hero stays near the center of the screen while the world slides around them. That’s the illusion of scrolling - the hero isn’t really moving on screen, the world is.
-
Going Further
The combined game from the previous tutorial is functional but raw. This page covers the extensions that separate a working prototype from a game that feels good to play. Each section is self-contained — add the ones that fit your design.
Variable Jump Height
Fixed-height jumping feels mechanical. In most platformers, releasing the jump button early cuts the jump short. This gives players fine control over arc height and makes jumping feel responsive rather than automatic.
-
More Scrolling
The camera from the previous tutorial has one flaw: walk to the edge of the map and the camera keeps going, revealing the empty void beyond. Every great platformer stops scrolling at the map boundary so the world feels solid and complete. Let’s fix it!
Loading editor…Walk to a corner of the map - the camera stops cleanly at the edge and the hero keeps moving. That’s the
clamp. Two lines added toupdateCamera()and the void disappears. -
Stupid Enemy
A wall-bouncing enemy is the simplest moving threat: each frame, advance by
moveX/moveY; if the next position hits a solid tile, reverse direction. That’s the entire AI.Loading editor…Why simple enemies work
Pac-Man’s ghosts use simple chase and scatter rules. Mario’s Goombas walk in straight lines. Space Invaders move in formation. None of these are complex behaviours, but all of them create spatial and timing challenges for the player.
-
A Living World
Every piece from this series in one place. A tile world with movement, collision, a patrolling enemy, a key to find, a pushable block, and a locked door to earn your way through.
Loading editor…Everything from the series is here:
-
Going further
Four rooms. One key. Everything from this series working together as a designed sequence.
Loading editor…Four rooms, each asking something different of you: