Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Tilemaps and Cameras

Tilemap Basics

Build tile-based worlds in Phaser with tilemaps, tilesets and layers. Create a map from an array, read and change tiles, and paint tiles with the mouse.

Most 2D games with big levels do not place thousands of separate sprites. They cut the world into a grid of equal squares called tiles, and every square shows one picture from a shared sheet of pictures. A platformer's ground, a top-down dungeon's walls and a farming game's fields are all tilemaps. The grid is cheap to store (a table of numbers), cheap to draw (Phaser renders a whole layer efficiently) and easy to edit.

This lesson shows the three ideas behind Phaser's tilemap system, builds a map from a plain JavaScript array, and then reads and changes tiles while the game runs. The examples load Phaser 4 from a CDN. Because the lesson sandbox cannot load your own image files, every tileset here is drawn in code, but the API calls are identical when your tileset is a PNG.

The three ingredients

A tilemap is made of three separate things, and mixing them up is the most common beginner mistake:

  • Tileset: one image that holds every tile picture in a grid, for example 4 tiles of 32 by 32 pixels in a 128 by 32 image. Tile number 0 is the first picture, number 1 the second, and so on.
  • Map data: a table of numbers. Each number says which tileset picture goes in that cell. The special value -1 means "empty".
  • Layer: a drawable made from the map data and a tileset. A map can have several layers (ground, decoration, walls) drawn on top of each other.
flowchart LR
  T["Tileset image<br/>(tile pictures)"] --> L["Tilemap layer"]
  D["Map data<br/>(grid of numbers)"] --> L
  L --> S["What the player sees"]

The layer combines a grid of numbers with a tileset image.

Drawing a tileset in code

A real project keeps its tileset as a PNG and loads it in preload() with this.load.image('tiles', 'tiles.png'). Here we draw four 32 pixel squares with a Graphics object and turn them into a texture called tiles:

JavaScript
function makeTileset(scene) {
  const g = scene.add.graphics();
  const colors = [0x3b82f6, 0x22c55e, 0xb45309, 0x6b7280];
  colors.forEach((c, i) => {
    g.fillStyle(c, 1).fillRect(i * 32, 0, 32, 32);
    g.lineStyle(1, 0x000000, 0.25).strokeRect(i * 32, 0, 32, 32);
  });
  g.generateTexture('tiles', 128, 32);
  g.destroy();
}

After this call the texture tiles exists in Phaser's texture manager and behaves exactly like a loaded image. Tile 0 is water (blue), 1 is grass (green), 2 is dirt (brown) and 3 is stone (gray).

Creating a map from an array

this.make.tilemap() builds a map. With the data option you give it a two-dimensional array: the outer array holds rows from top to bottom, and each inner array holds the tiles of that row from left to right.

A map from a plain array

Read the steps in order:

  1. make.tilemap({ data, tileWidth, tileHeight }) creates the map object. It does not draw anything yet.
  2. map.addTilesetImage('tiles') connects the texture called tiles to the map and returns a Tileset.
  3. map.createLayer(0, tileset, 0, 0) creates the first (and only) layer at screen position 0,0. A layer is a game object, so you can move it, scale it, hide it or set its depth like a sprite.

getTileAt(x, y) takes tile coordinates, not pixels. Column 3, row 2 is the dirt tile with index 2 in the example above.

Tile coordinates run x to the right and y downward, starting at 0 in the top-left corner, just like screen pixels. Always say "tile (3, 2)" for grid cells and "pixel (96, 64)" for screen positions, so that you never mix the two.

Reading and changing tiles

Once a layer exists you can query and edit it at any time. These are the methods you will use most:

Method What it does
getTileAt(tx, ty) Returns the Tile at a grid cell, or null if it is empty
getTileAtWorldXY(x, y) The same, but you give pixel coordinates
putTileAt(index, tx, ty) Places a tile with that index at a grid cell
putTileAtWorldXY(index, x, y) Places a tile at pixel coordinates
removeTileAt(tx, ty) Makes a cell empty
fill(index, tx, ty, w, h) Fills a rectangle of cells
replaceByIndex(from, to) Changes every tile of one kind into another
randomize(tx, ty, w, h, indexes) Fills an area with random tiles from a list
worldToTileXY(x, y) Converts pixels to grid coordinates
tileToWorldXY(tx, ty) Converts grid coordinates to the pixel position of a tile's corner

Every Tile object also carries useful fields: tile.index, tile.x, tile.y (grid position), tile.pixelX, tile.pixelY, tile.properties and flags like tile.collides, which the next lesson uses.

Painting tiles with the mouse

The next example turns the map into a tiny editor. A pointer press places the selected tile, and the number keys choose which tile you paint with. It also uses replaceByIndex to flood all water with stone when you press the space bar, and prints the result.

Tile painter

This version builds the map without a data array: make.tilemap({ tileWidth, tileHeight, width, height }) makes an empty grid, and createBlankLayer('ground', tileset, 0, 0) adds a named layer you can fill. That is the right approach for maps that you generate or edit at run time. Click the canvas first so that it receives the keyboard focus.

Layers, depth and tile size

A map can hold more than one layer. You create each one with createLayer or createBlankLayer, and later layers draw over earlier ones. Use a ground layer with solid colors, and a decoration layer where empty cells (-1) let the ground show through. Because layers are ordinary game objects, layer.setDepth(10) puts one in front of your sprites, which is how treetops and roofs hide the player.

Tile size matters for pixel art. If your art is 16 by 16 pixels but you want it big on screen, keep the tile size at 16 and scale the layer: layer.setScale(2). For crisp edges set pixelArt: true in the game config, which turns off texture smoothing.

Common mistakes

  • Wrong tile size. If the tileset image is 128 by 32 and you pass tileWidth: 16, Phaser slices it into 16-pixel tiles and every index is off. The size in make.tilemap and the real tileset grid must match.
  • Mixing pixels and tiles. getTileAt(96, 64) looks at tile column 96, which is far outside the map and returns null. Use getTileAtWorldXY for pixel positions.
  • Reading a null tile. An empty cell returns null, so write layer.getTileAt(x, y)?.index when a cell may be empty.
  • Texture not ready. addTilesetImage needs the texture to exist. Load it in preload() or generate it before you create the map.
  • Off-by-one in sizes. A map of width: 15 has tile columns 0 to 14. Reading column 15 gives null.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a tilemap built from a data array, what does the value -1 mean?

    A negative index marks an empty cell. getTileAt returns null for it and nothing is drawn, so lower layers show through.
  2. 2. Which call creates the visible, drawable object from a map and a tileset?

    make.tilemap makes the map object, addTilesetImage links the image, and createLayer produces the layer game object that is actually rendered.
  3. 3. A tile is 32 by 32 pixels. Which tile does getTileAtWorldXY(100, 70) look at?

    100 / 32 is 3.1, so column 3, and 70 / 32 is 2.2, so row 2. World methods divide pixel coordinates by the tile size and round down.
  4. 4. You want fast, in-game map edits for a level generator. What is a good way to start?

    A blank layer is an editable grid. The layer methods change cells cheaply, and Phaser redraws only what is needed.

Summary

  • A tilemap is a grid of numbers (map data) plus a tileset image; a layer draws them together.
  • make.tilemap, addTilesetImage and createLayer are the three calls that build a visible map.
  • Tile coordinates count cells from the top-left; world coordinates count pixels. Use the ...WorldXY methods for pixels.
  • putTileAt, fill, replaceByIndex and randomize edit a layer at run time, and createBlankLayer starts from an empty grid.
  • Layers are game objects, so you can scale them and set their depth to place them behind or in front of sprites.

Next: Maps from the Tiled Editor