360 Secure SkillHub
360 安全技能中心

tilemaps

提供 Phaser 4 中 Tiled/CSV 瓦片地图的加载、图层创建、瓦片读写、碰撞、对象层、等距/六边形地图和 GPU 层用法,并列出常见错误与限制,适合在编写或调试瓦片地图代码时查阅。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:36

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/tilemaps
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
tilemaps
description
Tile maps in Phaser 4: load.tilemapTiledJSON and load.tilemapCSV, make.tilemap, addTilesetImage, createLayer and createBlankLayer, TilemapGPULayer, getTileAt, putTileAt, removeTileAt, getTilesWithinShape, tile collision with setCollisionByProperty and setCollision, Arcade colliders, object layers with createFromObjects, isometric, hexagonal and staggered maps, and layer culling. Use when building a level, platformer or dungeon map, a procedural or editable map, or placing enemies and pickups from Tiled. Corrects: Tiled tile IDs are not tile indexes, an overlap with a layer includes empty tiles, putTileAt keeps the old tile's properties, and the GPU layer is WebGL, orthogonal and single-tileset. Triggers on: tilemap, Tiled, tileset, tile layer, tile collision, object layer.
metadata
{"phaser-version":"4.3.0"}

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) and this.add.tilemap(key) both return a Tilemap. Neither is on the display list.
  • In Tiled, embed the tilesets in the map. External .tsx tilesets 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)

  • tilesetName is the tileset's name inside Tiled, not a file name. If it doesn't match, the method returns null and logs the map's tilesets. key defaults to tilesetName.
  • 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)

  • layerID is the Tiled layer name or its index. Layers inside a Tiled group are named 'Group/Layer'. An unknown name returns null and logs the valid names.
  • Each layer can be created once. A second call returns null.
  • x and y default to the layer's offset in Tiled, not (0, 0).
  • Layers draw in creation order. Use setDepth to 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'), then this.make.tilemap({ key: 'cave', tileWidth: 32, tileHeight: 32 }) and createLayer(0, ...).
  • insertNull: true in the make.tilemap config stores empty cells as null instead of index -1 Tiles, which saves memory on large sparse maps. putTileAt still works on those cells. getTileAt(x, y, true) returns null for them, and an overlap skips them.

Tiles

  • tile.index is the global tile index. In a Tiled map it is the tile's ID in Tiled plus its tileset's firstgid (usually 1). The ID shown in Tiled's tileset editor is not the index. -1 is an empty cell.
  • tile.x and tile.y are in tiles. tile.pixelX and tile.pixelY are relative to the layer. tile.getCenterX() and tile.getCenterY() are in world space.
  • tile.properties is a plain object, copied from the tileset when the map is parsed.
  • Tiled's flip and rotate flags arrive as tile.rotation (radians) and tile.flipX. A vertical flip in Tiled is rotation = Math.PI with flipX = true, so tile.flipY stays false.
  • tile.tint, tile.tint2 (4.2) and tile.tintMode work on a CPU layer. layer.setTint(color, tileX, tileY, width, height), setTint2 and setTintMode set 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): nonNull is the third positional argument. true returns an index -1 Tile for an empty cell instead of null. Outside the layer, and for null cells, the result is still null.
  • putTileAt changes the index of the Tile in that cell. It doesn't refresh properties, and the tile collides only if its index was recorded by setCollision, setCollisionBetween or setCollisionByExclusion. Only put indexes that one of the map's tilesets contains: an unknown index throws.
  • removeTileAt(tileX, tileY, replaceWithNull, recalculateFaces): replaceWithNull defaults to true, so the cell becomes null. Pass false to leave an index -1 Tile.
  • TypeScript: since 4.3, getTileAt, getTileAtWorldXY, putTileAt, putTileAtWorldXY, removeTileAt and removeTileAtWorldXY return Tile | null. With strictNullChecks, check the result before using it.
  • Every tile method also exists on the Tilemap with an extra last layer argument, 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. Their filteringOptions are { isNotEmpty, isColliding, hasInterestingFace }. Editing: fill, putTilesAt, randomize, weightedRandomize, replaceByIndex, swapByIndex, copy, shuffle. Coordinates: worldToTileXY, tileToWorldXY. See src/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.index or 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) and tile.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 returns true cancels the collision with that tile.
  • Only the index methods record indexes for tiles placed later. setCollisionByExclusion records only the indexes in the layer when it's called. setCollisionByProperty and setCollisionFromCollisionGroup record nothing, so set tile.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 collisionCategory and collisionMask like 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, name and type pick the objects. With none of them, every object is used.
  • classType defaults to Phaser.GameObjects.Sprite, which has no body. It is called as new classType(scene) and then positioned and textured, so a custom class's constructor must work with only the Scene.
  • key and frame set the texture. A tile object (one with a gid) given no key uses its tileset's texture with gid - firstgid as the frame. That frame exists only if the tileset image was also loaded as a spritesheet, so otherwise pass key and frame.
  • container adds the objects to a Container instead of the Scene. ignoreTileset skips the tileset texture and properties.
  • sortByY sorts 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 with setData otherwise. Read it with getData('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.orientation with Phaser.Tilemaps.Orientation.ORTHOGONAL, ISOMETRIC, STAGGERED or HEXAGONAL.
  • 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, createFromObjects places isometric objects where Tiled does, so remove any manual offset. Before 4.3, worldToTileXY on staggered maps returned the wrong tile for most points.
  • Not supported on these maps: TilemapGPULayer, Arcade tile collision, renderDebug, and getTilesWithinShape on 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.AUTO can 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.tilesDrawn and layer.tilesTotal give the counts for the last frame.
  • 4.3 fixed Camera.worldView when 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). Use setCollisionByProperty to 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 putTileAt keeps the old tile's properties, and collides only if its index was recorded.
  • removeTileAt leaves null by default, so getTileAt(x, y, true) returns null for that cell.
  • 4.3 fixed tiles with flipY being drawn shifted sideways in WebGL.