This lesson was updated. Reset to the new version?
This browser isn't keeping your edits, so they're lost when you leave the page.
Pokémon-1 splits the map into layers, so walls stop the player, and roofs and treetops are drawn over them. The field of grass is now 24 × 20 tiles, so a camera follows the player around it.
Three Layers
A map has three layers of tiles, each the size of the whole map. GameMap in src/objects/GameMap.js makes one Layer for each:
- Bottom is the ground, such as grass and paths. Every cell has a tile.
- Collision holds what the player can’t walk through, such as walls, fences, and tree trunks.
- Top holds what the player walks behind, such as roofs and the leaves of trees.
render() draws the Bottom and Collision layers, then the player, then the Top layer over them:
69render(context, camera) {70 this.bottomLayer.render(context, camera);71 this.collisionLayer.render(context, camera);72 this.player.render(context);73 this.topLayer.render(context, camera);So a player walking along the row above a tree’s trunk is drawn under its leaves, and the trunk stops them walking through the tree. The camera comes from The Camera below.
Tile IDs
town.tmj is JSON. Each layer lists one tile id per cell, row by row, the same flat layout as Zelda’s rooms. Here’s a town’s file, trimmed:
{ "width": 24, "height": 20, "layers": [ { "name": "Bottom", "data": [4039, 4039, 4039 /* … */] }, { "name": "Collision", "data": [4553, 4552, 0 /* … */] }, { "name": "Top", "data": [0, 0, 0 /* … */] } ]}Tiled numbers tiles from 1 and saves an empty cell as 0. Layer in src/objects/Layer.js turns each ID into a Tile, takes one off to get the sprite’s index, and keeps null for an empty cell:
24// Tiled numbers tiles from 1 and uses 0 for an empty cell.25this.tiles = tileIds.map((id) =>26 id === 0 ? null : this.createTile(id - 1),27);The tiles come from three sheets, numbered one after the other, so each sheet’s tiles start where the last one’s end. tilesets in src/config/tiles.js lists each sheet with the ID of its first tile, so loadTileSprites() in src/frames.js can cut them all into one list of sprites:
9export const tilesets = [10 { image: ImageName.Tileset1, firstId: 1, columns: 64, tileCount: 4032 },11 { image: ImageName.Tileset2, firstId: 4033, columns: 28, tileCount: 1316 },12 { image: ImageName.MapCells, firstId: 5349, columns: 39, tileCount: 546 },13];Loading the Map
loadMaps() in src/services/maps.js reads each .tmj file with fetch(), the browser’s function for loading a file from a URL. fetch() and response.json() both return promises, so each one is awaited:
17export async function loadMaps(mapFiles) {18 await Promise.all(19 mapFiles.map(async ({ name, path }) => {20 const response = await fetch(path);21 /** @type {TiledMap} */22 const { width, height, layers } = await response.json();23
24 maps[name] = {25 width,26 height,27 layers: {28 bottom: getLayerData(layers, "Bottom"),29 collision: getLayerData(layers, "Collision"),30 top: getLayerData(layers, "Top"),31 },32 };33 }),34 );35}Promise.all() loads every map at once and resolves when they’ve all arrived, the way Match-3 ran its falling tiles together. getLayerData() finds each layer by name, and throws an error if one is missing, so a broken map stops the game at start-up instead of drawing nothing.
main.js awaits loadMaps() before it pushes PlayState. Loading Tiled’s own file means a map you save in Tiled shows up on the next page refresh.
The Camera
The screen only fits 15 × 11 tiles, and the town is 24 × 20, so a camera follows the player.
getCameraPosition() in src/services/camera.js works out where the view’s top left corner is on the map, in pixels. For each axis, it puts the player in the middle of the screen, then stops the view at the map’s edges:
12function getAxisOffset(focus, viewSize, mapSize) {13 if (mapSize <= viewSize) {14 return (mapSize - viewSize) / 2;15 }16
17 return Math.min(Math.max(focus - viewSize / 2, 0), mapSize - viewSize);18}focus is the centre of the player’s tile, so focus - viewSize / 2 is where the view would start with the player in the middle. Math.max(…, 0) stops the view at the left or top edge, and Math.min(…, mapSize - viewSize) stops it at the right or bottom edge. Near a corner, the player walks off the centre of the screen instead. A map smaller than the screen is centred.
render() in src/states/PlayState.js moves the canvas by the camera before it draws the map:
60const { map, player } = this;61const camera = getCameraPosition(62 player.canvasPosition,63 map.pixelWidth,64 map.pixelHeight,65);66
67context.save();68context.fillStyle = Colour.Black;69context.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);70context.translate(-camera.x, -camera.y);71map.render(context, camera);72context.restore();context.translate() shifts everything drawn after it, so the map and the player draw at their map positions. restore() undoes the shift. The camera is worked out in render(), not update(), because game.timer moves the player’s tweens after the states update, so a camera moved in update() would lag a frame behind.
Only around 165 of a layer’s 480 tiles fit on screen. Layer.render() in src/objects/Layer.js works out which columns and rows the camera can see, and only draws those:
63render(context, camera) {64 const left = Math.max(0, Math.floor(camera.x / TILE_SIZE));65 const top = Math.max(0, Math.floor(camera.y / TILE_SIZE));66 const right = Math.ceil((camera.x + CANVAS_WIDTH) / TILE_SIZE);67 const bottom = Math.ceil((camera.y + CANVAS_HEIGHT) / TILE_SIZE);Skipping what can’t be seen is called culling. Drag the player around the town, or move them with the sliders. The red dashed box is where the view would be with the player in the middle, and the orange box is where getCameraPosition() puts it:
Walls
isTileOpen() in src/objects/GameMap.js decides where the player can go. In Pokémon-0 it only checked that the tile was on the map. Now it returns !this.isCollisionTile(x, y), so a tile is open when the Collision layer has nothing there:
40isCollisionTile(x, y) {41 return this.collisionLayer.getTile(x, y) !== null;42}That one check also keeps the player on the map. Layer.getTile() returns undefined for a position outside the map, and undefined isn’t null, so the edge counts as a wall:
85getTile(x, y) {86 if (x < 0 || y < 0 || x >= this.width || y >= this.height) {87 return undefined;88 }89
90 return this.tiles[x + y * this.width];91}The tiles are one flat array, so without the bounds check, column 24 of a 24-wide map would be index 24 + y × 24, which is column 0 of the next row.
Bumping
Walking into a wall makes handleMovement() in src/states/player/PlayerWalkState.js change to PlayerBumpState, so the player walks on the spot:
59if (player.isValidMove(target)) {60 // void: nothing waits for this step, so the game loop carries on.61 void this.walkTo(target);62} else {63 player.changeState(PlayerStateName.Bump);64}PlayerBumpState in src/states/player/PlayerBumpState.js plays the walk cycle without moving the player. playBumpSound() plays the thud each time currentFrame reaches a foot pose, 0 or 2:
64playBumpSound() {65 const frame = this.animation.currentFrame;66
67 if (frame !== this.previousFrame && (frame === 0 || frame === 2)) {68 this.game.sounds.play(SoundName.PlayerBump);69 }70
71 this.previousFrame = frame;72}update() goes back to idle when the key is let go, and to walking when the player turns or the tile ahead opens up.
Build your town
The map in assets/maps/town.tmj is 24 × 20 tiles of grass, so nothing stops the player. Build a town on it in Tiled:
- Download the Tiled starter, unzip it, and open
maps/town.tmjin Tiled. - Paint houses, fences, and tree trunks on the Collision layer, and roofs and treetops on the Top layer. Repaint the Bottom layer if you like.
- Save, open the saved
town.tmjin a text editor, and paste all of it overassets/maps/town.tmjhere.
A few things in Tiled break the map loader:
- Don’t flip or rotate tiles (the X, Y, and Z keys).
- Don’t add, remove, or reorder tilesets.
- Keep the three layers named Bottom, Collision, and Top, and don’t put them in a group.
- Leave the map’s Tile Layer Format as CSV, and don’t make the map Infinite.
The Challenge tab gets a ✓ once you walk into a tile on the Collision layer. The edge of the map doesn’t count.
Select the Collision layer in Tiled’s Layers panel before you paint. Tiles painted while Bottom or Top is selected look the same but block nothing.
Save in Tiled with Ctrl+S (Cmd+S on a Mac) before you open town.tmj in the text editor, so you copy the map you just painted.
In assets/maps/town.tmj here, select everything with Ctrl+A (Cmd+A on a Mac) before you paste, so no part of the old map is left over. Then walk straight into a tile you painted on the Collision layer.