Tilemaps
A Tilemap holds the parsed map data and is not drawn. Its layers, TilemapLayer (CPU, every renderer and orientation) or TilemapGPULayer (WebGL, orthogonal), are the Game Objects that draw tiles. Most tile methods live on TilemapLayerBase, shared by both.
Source: src/tilemaps/Tilemap.js, src/tilemaps/TilemapLayerBase.js, src/tilemaps/TilemapLayer.js, src/tilemaps/TilemapGPULayer.js, src/tilemaps/Tile.js, src/tilemaps/Tileset.js, src/tilemaps/components/, src/tilemaps/parsers/tiled/. Related: physics-arcade, physics-matter, loading-assets, cameras.
Quick start
A platformer level from Tiled, with Arcade Physics enabled in the game config.
class Level extends Phaser.Scene {
preload() {
this.load.tilemapTiledJSON('level1', 'assets/level1.json');
this.load.image('tiles', 'assets/tiles.png');
this.load.image('player', 'assets/player.png');
}
create() {
const map = this.make.tilemap({ key: 'level1' });
const tileset = map.addTilesetImage('terrain', 'tiles'); // tileset name in Tiled, texture key
const ground = map.createLayer('Ground', tileset); // layer name in Tiled
ground.setCollisionByProperty({ collides: true }); // a custom bool set in Tiled's tileset editor
this.player = this.physics.add.sprite(100, 100, 'player');
this.physics.add.collider(this.player, ground);
this.physics.world.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
this.cameras.main.startFollow(this.player);
}
}
The other snippets continue this one: map, tileset, ground and this.player come from here.
this.make.tilemap(config)andthis.add.tilemap(key)both return a Tilemap. Neither is on the display list.- In Tiled, embed the tilesets in the map. External
.tsxtilesets aren't loaded. Compressed layer data (zlib, gzip, zstd) is skipped with a warning, so save layers as CSV or uncompressed Base64. Infinite maps work.
Tilesets and layers
map.addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset)
tilesetNameis the tileset's name inside Tiled, not a file name. If it doesn't match, the method returnsnulland logs the map's tilesets.keydefaults totilesetName.- A Tiled map supplies the tile size, margin and spacing. Pass them only to override.
- The Tileset uses the whole texture image. Atlas frames are ignored, and a multi-atlas texture isn't supported (only its first image is used). Use the DynamicTexture workaround below.
- Image collection tilesets ("Collection of Images" in Tiled) are parsed. Each image becomes its own Tileset, named by the image path as written in the JSON. Since 4.3 they keep their tile properties, type and collision group.
const tree = map.addTilesetImage('../img/tree.png', 'tree'); // name = the image path in the JSON
const props = map.createLayer('Props', [tileset, tree]); // a CPU layer can take several tilesets
map.createLayer(layerID, tileset, x, y, gpu)
layerIDis the Tiled layer name or its index. Layers inside a Tiled group are named'Group/Layer'. An unknown name returnsnulland logs the valid names.- Each layer can be created once. A second call returns
null. xandydefault to the layer's offset in Tiled, not (0, 0).- Layers draw in creation order. Use
setDepthto put sprites between them.
A tileset from atlas frames
A Tileset needs one image laid out as a grid. To build one from atlas or multi-atlas frames, stamp them into a DynamicTexture in the order the Tiled tileset expects.
const size = 32;
const cols = 4;
const names = ['grass', 'dirt', 'water', 'stone', 'sand', 'snow']; // frames of the 'world' atlas
const sheet = this.textures.addDynamicTexture('terrainSheet', cols * size, Math.ceil(names.length / cols) * size);
names.forEach((name, i) => {
sheet.stamp('world', name, (i % cols) * size, Math.floor(i / cols) * size, { originX: 0, originY: 0 });
});
sheet.render(); // v4: nothing is drawn into a DynamicTexture until render()
const terrain = map.addTilesetImage('terrain', 'terrainSheet', size, size);
Maps without Tiled
// From a 2D array. -1 is an empty cell. For a non-Tiled map, index 0 is the tileset's first tile.
const level = [
[ -1, -1, -1, -1, -1 ],
[ -1, 4, -1, -1, -1 ],
[ 0, 1, 1, 1, 2 ]
];
const arrayMap = this.make.tilemap({ data: level, tileWidth: 32, tileHeight: 32 });
const tiles = arrayMap.addTilesetImage('tiles'); // the key defaults to the name
const layer = arrayMap.createLayer(0, tiles);
layer.setCollision([0, 1, 2]);
// A blank map for procedural levels. Every cell starts as an empty Tile, index -1.
const proc = this.make.tilemap({ tileWidth: 32, tileHeight: 32, width: 64, height: 24 });
const procTiles = proc.addTilesetImage('tiles');
const world = proc.createBlankLayer('world', procTiles);
world.fill(1, 0, 23, 64, 1); // index, tileX, tileY, width, height
world.randomize(0, 10, 64, 4, [-1, -1, -1, 7]);
world.setCollision([1, 7]);
- CSV:
this.load.tilemapCSV('cave', 'assets/cave.csv'), thenthis.make.tilemap({ key: 'cave', tileWidth: 32, tileHeight: 32 })andcreateLayer(0, ...). insertNull: truein themake.tilemapconfig stores empty cells asnullinstead of index -1 Tiles, which saves memory on large sparse maps.putTileAtstill works on those cells.getTileAt(x, y, true)returnsnullfor them, and an overlap skips them.
Tiles
tile.indexis the global tile index. In a Tiled map it is the tile's ID in Tiled plus its tileset'sfirstgid(usually 1). The ID shown in Tiled's tileset editor is not the index. -1 is an empty cell.tile.xandtile.yare in tiles.tile.pixelXandtile.pixelYare relative to the layer.tile.getCenterX()andtile.getCenterY()are in world space.tile.propertiesis a plain object, copied from the tileset when the map is parsed.- Tiled's flip and rotate flags arrive as
tile.rotation(radians) andtile.flipX. A vertical flip in Tiled isrotation = Math.PIwithflipX = true, sotile.flipYstaysfalse. tile.tint,tile.tint2(4.2) andtile.tintModework on a CPU layer.layer.setTint(color, tileX, tileY, width, height),setTint2andsetTintModeset them on a region. The tint modes are in game-object-components. A GPU layer ignores tile tint, alpha and visibility.
Get, put and remove
this.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer) => {
const tile = ground.getTileAtWorldXY(pointer.worldX, pointer.worldY); // Tile or null
if (tile && tile.properties.breakable) {
ground.removeTileAt(tile.x, tile.y);
}
});
const placed = ground.putTileAt(12, 5, 8); // index, tileX, tileY. null outside the layer
if (placed) {
placed.properties = { ...placed.tileset?.getTileProperties(12) }; // putTileAt keeps the old properties
if (placed.properties.collides) {
placed.setCollision(true); // setCollisionByProperty doesn't cover tiles placed later
}
}
getTileAt(tileX, tileY, nonNull):nonNullis the third positional argument.truereturns an index -1 Tile for an empty cell instead ofnull. Outside the layer, and fornullcells, the result is stillnull.putTileAtchanges the index of the Tile in that cell. It doesn't refreshproperties, and the tile collides only if its index was recorded bysetCollision,setCollisionBetweenorsetCollisionByExclusion. Only put indexes that one of the map's tilesets contains: an unknown index throws.removeTileAt(tileX, tileY, replaceWithNull, recalculateFaces):replaceWithNulldefaults totrue, so the cell becomesnull. Passfalseto leave an index -1 Tile.- TypeScript: since 4.3,
getTileAt,getTileAtWorldXY,putTileAt,putTileAtWorldXY,removeTileAtandremoveTileAtWorldXYreturnTile | null. WithstrictNullChecks, check the result before using it. - Every tile method also exists on the Tilemap with an extra last
layerargument, acting on the current layer (map.setLayer) when it's left out. Call them on the layer instead. - Regions and searches:
getTilesWithin,getTilesWithinWorldXY,filterTiles,findTile,forEachTile. TheirfilteringOptionsare{ isNotEmpty, isColliding, hasInterestingFace }. Editing:fill,putTilesAt,randomize,weightedRandomize,replaceByIndex,swapByIndex,copy,shuffle. Coordinates:worldToTileXY,tileToWorldXY. Seesrc/tilemaps/TilemapLayerBase.js.
Tiles inside a shape
const blast = new Phaser.Geom.Circle(this.player.x, this.player.y, 96); // world coordinates
ground.getTilesWithinShape(blast, { isNotEmpty: true })
.filter(tile => tile.properties.breakable)
.forEach(tile => ground.removeTileAt(tile.x, tile.y));
getTilesWithinShape(shape, filteringOptions, camera) takes a Circle, Line, Rectangle or Triangle in world coordinates. Since 4.3 it works on isometric layers, testing each tile's diamond. On hexagonal and staggered layers it logs a warning and returns [].
Collision with Arcade Physics
ground.setCollisionByProperty({ collides: true }); // tiles whose properties match
ground.setCollision([1, 2, 3]); // by index
ground.setCollisionBetween(1, 50); // by index, inclusive
ground.setCollisionByExclusion([-1]); // every index now in the layer, except these
ground.setCollisionFromCollisionGroup(); // tiles with shapes in Tiled's collision editor
this.physics.add.collider(this.player, ground);
this.physics.add.overlap(this.player, ground, (player, tile) => {
if (tile.properties.spikes) {
player.setTint(0xff0000);
}
});
- A collider tests only tiles marked as colliding, so mark them first. An overlap tests every tile under the body, colliding or not, including empty ones with an index of -1. Check
tile.indexor a property in the callback. - The callbacks always get
(sprite, tile), whichever order you pass them in. - Tile callbacks:
layer.setTileIndexCallback(indexes, callback, context),layer.setTileLocationCallback(tileX, tileY, width, height, callback, context)andtile.setCollisionCallback(callback, context). They run only while a collider or overlap exists between the body and the layer: for colliding tiles with a collider, and for every tile with an overlap. A tile callback which returnstruecancels the collision with that tile. - Only the index methods record indexes for tiles placed later.
setCollisionByExclusionrecords only the indexes in the layer when it's called.setCollisionByPropertyandsetCollisionFromCollisionGrouprecord nothing, so settile.setCollision(true)on tiles you place. - One-way tile:
tile.setCollision(false, false, true, false)(left, right, up, down) collides on the top face only. - A layer has
collisionCategoryandcollisionMasklike a body, both 1 by default. See physics-arcade. - Arcade treats each tile as a box, so tile collision is only correct on orthogonal maps.
- Matter: call
this.matter.world.convertTilemapLayer(ground)after setting collision. See physics-matter.
const debug = this.add.graphics().setDepth(100);
ground.renderDebug(debug, { tileColor: null }); // also: collidingTileColor, faceColor (Phaser.Display.Color or null)
renderDebug draws once, for orthogonal maps. Use a Graphics just for it, and clear() it before calling again.
Object layers
const coins = map.createFromObjects('Items', { name: 'coin', key: 'coin', classType: Phaser.Physics.Arcade.Sprite });
const coinGroup = this.physics.add.staticGroup(coins);
this.physics.add.overlap(this.player, coinGroup, (player, coin) => coin.disableBody(true, true));
const spawn = map.findObject('Items', obj => obj.name === 'spawn');
this.player.setPosition(spawn.x, spawn.y);
map.createFromObjects(layerName, config, useTileset), where config is an object or an array of them:
id,gid,nameandtypepick the objects. With none of them, every object is used.classTypedefaults toPhaser.GameObjects.Sprite, which has no body. It is called asnew classType(scene)and then positioned and textured, so a custom class's constructor must work with only the Scene.keyandframeset the texture. A tile object (one with agid) given nokeyuses its tileset's texture withgid - firstgidas the frame. That frame exists only if the tileset image was also loaded as a spritesheet, so otherwise passkeyandframe.containeradds the objects to a Container instead of the Scene.ignoreTilesetskips the tileset texture and properties.sortByYsorts by y. It was ignored before 4.3, and it sorts the map's object array in place.- A custom property is set on the Game Object if it has a property of that name (
alpha,depth), and stored withsetDataotherwise. Read it withgetData('hp').
Raw objects: map.getObjectLayer('Items').objects, map.findObject(layer, callback) and map.filterObjects(layer, callback). On a raw object, properties is Tiled's array of { name, type, value }, not an object.
Isometric, hexagonal and staggered maps
- The orientation comes from the JSON. Compare
map.orientationwithPhaser.Tilemaps.Orientation.ORTHOGONAL,ISOMETRIC,STAGGEREDorHEXAGONAL. - Use the layer's own coordinate methods (
worldToTileXY,tileToWorldXY,getTileAtWorldXY). They switch on the orientation. On an isometric layer,getIsoTileAtWorldXY(worldX, worldY, false)tests the tile's base instead of its top face. - Since 4.3,
createFromObjectsplaces isometric objects where Tiled does, so remove any manual offset. Before 4.3,worldToTileXYon staggered maps returned the wrong tile for most points. - Not supported on these maps: TilemapGPULayer, Arcade tile collision,
renderDebug, andgetTilesWithinShapeon hexagonal and staggered maps.
TilemapGPULayer
// In place of the Quick start's createLayer call
const gpu = this.renderer.type === Phaser.WEBGL;
const ground = map.createLayer('Ground', tileset, 0, 0, gpu); // TilemapGPULayer in WebGL, TilemapLayer in Canvas
- WebGL only. It throws under Canvas, and
Phaser.AUTOcan fall back to Canvas, so pass the flag as above. - One tileset with one image per layer. If you pass an array, it warns and uses the first. Orthogonal maps only. Up to 4096x4096 tiles.
- It supports flipped and animated tiles and, since 4.3, rotated tiles in quarter turns. Other angles are rounded to the nearest 90 degrees, and a non-square tile turned 90 or 270 degrees is stretched to fit its cell.
- Edits don't show until you call
layer.generateLayerDataTexture(). Queries and collision work as on a CPU layer. - It ignores tile tint, alpha and visibility. Layer alpha works.
- With LINEAR filtering it draws smooth edges between tiles, with no seams. With NEAREST (
pixelArt: true) it draws sharp pixels. It always samples the full-size tileset, so mipmaps are not used. - It draws the layer as one quad, so it doesn't cull. Its cost depends on the screen area it covers, not on the number of tiles.
- 4.3 fixed several GPU layer bugs: a layer drawn at twice its position, tilesets whose margin and spacing differ, animated tiles other than the first, empty cells drawn with a tileset pixel, lines between tiles with mipmaps, bleeding on flipped tiles, low-precision Android GPUs, and maps made with
insertNull, which threw.
Culling
A TilemapLayer draws only the tiles inside each camera's view, plus cullPaddingX and cullPaddingY tiles around it (default 1).
layer.setCullPadding(2, 2)widens it, in tiles. Use it when tiles are taller or wider than the map's tile size, or when the camera rotates.layer.setSkipCull()draws every tile. A layer with a scroll factor other than 1 is never culled.layer.tilesDrawnandlayer.tilesTotalgive the counts for the last frame.- 4.3 fixed
Camera.worldViewwhen the camera origin isn't 0.5 and the zoom isn't 1, which culled visible edge tiles.
Gotchas
- Tile indexes in a Tiled map are global ids (ID in Tiled +
firstgid). UsesetCollisionByPropertyto avoid hard-coding them. - Tileset and layer names must match Tiled exactly, including case.
- An overlap with a layer reports empty and non-colliding tiles. A collider reports only colliding tiles.
- A tile placed with
putTileAtkeeps the old tile'sproperties, and collides only if its index was recorded. removeTileAtleavesnullby default, sogetTileAt(x, y, true)returnsnullfor that cell.- 4.3 fixed tiles with
flipYbeing drawn shifted sideways in WebGL.
