-
Notifications
You must be signed in to change notification settings - Fork 4
Tilemaps
samme edited this page Aug 5, 2023
·
32 revisions
- Modular Game Worlds in Phaser 3 — Static Maps
- Modular Game Worlds in Phaser 3 — Dynamic Platformer
- Modular Game Worlds in Phaser 3 — Procedural Dungeon
- 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
- Layer data: a 2-dimensional array (grid) of tiles, identified by index or name
- Tilemap layer: a game object on the scene display list, rendering one map layer data
The basic procedure is:
- Load a tileset image
- Load a tileset file, if using one
- Create a tilemap object
- Assign a tileset image to the tilemap
- Create a tilemap layer, specifying one or more tilesets for it
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.
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);
}
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));