Skip to content

Tilemaps

samme edited this page Aug 5, 2023 · 32 revisions

Summary

  • Tilemap file: a Tiled JSON or CSV file
  • Tilemap:
    • Layer data: a 2-dimensional array (grid) of tiles, identified by index or name
      • Tile: a tile placed on a map layer
    • Tileset: a mapping of tile IDs onto a tileset image
    • Object layer: a nonrenderable layer with object data, created in Tiled
  • Tilemap layer: a game object on the scene display list, rendering one map layer data

The basic procedure is:

  1. Load a tileset image
  2. Load a tileset file, if using one
  3. Create a tilemap object
  4. Assign a tileset image to the tilemap
  5. Create a tilemap layer, specifying one or more tilesets for it

Tileset images

Every tilemap layer needs at least one tileset image to render. You assign this to the map with addTilesetImage().

load.image() is fine for this, but you can also use load.spritesheet() (with the appropriate frame dimensions) if you want to use the tileset image as a multiframe texture for other game objects like sprites.

Tilemap from CSV

A CSV tilemap is a simple grid of tile IDs.

0,0,0,0
0,1,1,0
0,2,3,0

Load the map and tileset image.

function preload() {
  this.load.tilemapCSV('map', 'assets/tilemaps/csv/catastrophi_level2.csv');
  this.load.image('tiles', 'assets/tilemaps/tiles/catastrophi_tiles_16.png');
}

Create the tilemap from the CSV map key. Since the CSV data is just tile IDs, you need to give the tile dimensions that match the tileset image.

function create() {
  const map = this.make.tilemap({ key: 'map', tileWidth: 16, tileHeight: 16 });
  // …
}

Add the tileset image to the map and create a tilemap layer. A CSV map has only one layer data, at index 0.

function create() {
  // …
  const tileset = map.addTilesetImage('tiles');

  const layer = map.createLayer(0, tileset);
}

Object layers

Check your object properties

const map = this.add.tilemap(/*…*/);

const [firstObjectLayer] = map.objects;

console.info('Object properties in %s:', firstObjectLayer.name);
console.table(firstObjectLayer.objects);

console.info('Object custom properties in %s:', firstObjectLayer.name);
console.table(firstObjectLayer.objects.map(o => o.properties));

Collision shapes

Clone this wiki locally