tilemaps
phaserjs/phaser
在 Phaser 4 中处理瓦片地图时,请使用此技能。内容涵盖加载 Tiled JSON 地图、创建瓦片地图图层、瓦片碰撞、动态瓦片、瓦片属性以及瓦片地图摄像机剔除。触发条件:瓦片地图、Tiled、瓦片地图图层、瓦片碰撞、瓦片属性。
...展开全部Tilemaps
Phaser 的 Tilemaps 可根据 Tiled JSON、CSV 或原始 2D 数组渲染基于瓦片的关卡。一个
Tilemap对象用于存储已解析的地图数据,并提供添加贴图集、创建图层、设置碰撞以及查询贴图的方法。图层(TilemapLayer或TilemapGPULayer)是实际渲染地砖的游戏对象。Phaser 支持正交、等距、六边形和错位地图。
关键源路径: src/tilemaps/Tilemap.js, src/tilemaps/TilemapLayer.js, src/tilemaps/TilemapGPULayer.js, src/tilemaps/TilemapLayerBase.js, src/tilemaps/Tile.js, src/tilemaps/Tileset.js, src/tilemaps/TilemapFactory.js, src/tilemaps/components/, src/tilemaps/parsers/tiled/
相关技能:
../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md
快速入门
class GameScene extends Phaser.Scene {
preload() {
// Load the Tiled JSON and the tileset image
this.load.tilemapTiledJSON('map', 'assets/level1.json');
this.load.image('tiles', 'assets/tilesheet.png');
} create() {
// Create the tilemap from cached JSON
const map = this.add.tilemap('map'); // Link the tileset image to the tileset name used in Tiled
const tileset = map.addTilesetImage('tilesheet', 'tiles'); // Create a layer - layerID must match the layer name in Tiled
const ground = map.createLayer('Ground', tileset); // Enable collision on specific tile indexes
ground.setCollision([1, 2, 3]);
}
}
流程始终为:加载 JSON + 图片,创建瓦片地图,添加瓦片集图片,创建图层,设置碰撞。
核心概念
瓦片图与图层
A Tilemap 是一个数据容器,而非显示对象。它存储已解析的地图数据(图层、贴图集、对象),并提供用于操作这些数据的方法。一个 TilemapLayer 或 TilemapGPULayer 则是被添加到渲染列表中、负责渲染瓦片的实际游戏对象。
const map = this.add.tilemap('map'); // Data container (not rendered)
const layer = map.createLayer('Ground', tileset); // Game Object (rendered)
this.add.tilemap(key) 是注册在 GameObjectFactory上注册的工厂。它将操作委托给 ParseToTilemap ,该工厂会从缓存中读取数据并返回一个 Tilemap 实例。
贴图集
A Tileset (src/tilemaps/Tileset.js) 将(来自 Tiled 的)贴图集名称与已加载的纹理关联起来。它存储 firstgid、贴图尺寸、边距和间距。
// tilesetName: the name in Tiled's tileset panel
// key: the Phaser texture key (defaults to tilesetName if omitted)
const tileset = map.addTilesetImage('tilesetName', 'textureKey');// Override tile dimensions, margin, and spacing if needed
const tileset = map.addTilesetImage('name', 'key', 16, 16, 1, 2);
addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset) - 如果解析后的地图数据中已存在该贴图集名称,则用该纹理更新现有的 Tileset 对象;如果不存在(非 Tiled 地图),则创建一个新的 Tileset。
重要提示:Phaser Tiled 解析器不支持“图像集合”类型的贴图集。每个贴图集必须包含单张贴图集图像。
Tile 类
图层中的每个单元格都是一个 Tile 对象(src/tilemaps/Tile.js)。关键属性:
index- 贴图集中的贴图索引(为空时为 -1)x,y- 贴图坐标(以贴图为单位,而非像素)pixelX,pixelY- 相对于图层原点的像素位置width,height- 瓦片尺寸(以像素为单位)properties- 来自 Tiled 的自定义属性(对象)collideLeft,collideRight,collideUp,collideDown- 每条边对应的碰撞标志faceLeft,faceRight,faceTop,faceBottom- 用于碰撞优化的“感兴趣面”标志collisionCallback- 每块瓦片的碰撞回调函数tint- 色调颜色值(默认0xffffff)tintMode- 色调混合模式(默认TintModes.MULTIPLY)rotation- 旋转角度physics- 用于物理引擎特定数据的对象(例如:刚体)alpha,visible,flipX,flipY- 从混合类继承
TilemapGPULayer (v4.0.0)
TilemapGPULayer 是一款高性能的、仅支持 WebGL 的替代方案,用于替代 TilemapLayer。它通过着色器将整个图层渲染为单个四边形,因此几乎完全由 GPU 驱动。
// Pass gpu: true as the 5th argument to createLayer
const layer = map.createLayer('Ground', tileset, 0, 0, true);
功能:
- 每层仅支持单个贴图集(不支持多贴图集)
- 最大贴图集尺寸:4096×4096 个贴图
- 最大唯一贴图ID数:2^23(8,388,608)
- 支持贴图翻转和贴图动画
- 仅支持正交地图(不支持等轴/六边形/错位)
- 使用线性过滤平滑贴图边缘(无接缝)
- 采用最近邻滤波实现锐利像素
限制:
- 图层编辑结果不会自动显示。请调用
generateLayerDataTexture()。 - 仅限 WebGL 渲染器(不支持 Canvas 备用方案)
- 单个图层上无法使用多个图块集
// If you edit tiles on a GPU layer, regenerate the data texture:
gpuLayer.putTileAt(5, 10, 10);
gpuLayer.generateLayerDataTexture();
TilemapLayerBase
两者 TilemapLayer 和 TilemapGPULayer 继承 TilemapLayerBase (src/tilemaps/TilemapLayerBase.js),而该类又继承自 GameObject。该基类提供了所有瓦片查询、操作和碰撞方法。它包含以下组件混合类:Alpha、BlendMode、ComputedSize、Depth、ElapseTimer、Flip、GetBounds、Lighting、Mask、Origin、RenderNodes、Transform、Visible、ScrollFactor 以及 Arcade Physics Collision。
常见模式
基于 Tiled JSON 创建
preload() {
this.load.tilemapTiledJSON('map', 'assets/map.json');
this.load.image('tiles', 'assets/tileset.png');
}create() {
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('TilesetNameInTiled', 'tiles');
const layer = map.createLayer('LayerNameInTiled', tileset);
}
传入的 layerID 传递给 createLayer 必须与 Tiled 中的图层名称完全一致。组层下的子图层将按照 'ParentGroup/Layer' 命名约定进行扁平化。
多个图层
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('terrain', 'terrain-img');const background = map.createLayer('Background', tileset);
const ground = map.createLayer('Ground', tileset);
const foreground = map.createLayer('Foreground', tileset);// Layers are rendered in creation order. Use depth for finer control:
foreground.setDepth(10);
一个图层可以使用多个贴图集(仅限CPU图层):
const tiles1 = map.addTilesetImage('terrain', 'terrain-img');
const tiles2 = map.addTilesetImage('objects', 'objects-img');
const layer = map.createLayer('Ground', [tiles1, tiles2]);
创建空白图层
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('terrain', 'terrain-img');// createBlankLayer(name, tileset, x, y, width, height, tileWidth, tileHeight)
const layer = map.createBlankLayer('dynamic', tileset, 0, 0, 50, 50, 32, 32);// Fill it with tiles
layer.fill(1); // Fill entire layer with tile index 1
layer.putTileAt(5, 10, 10); // Place tile index 5 at tile coord (10, 10)
碰撞设置
有几种方法可以为Arcade Physics启用贴图碰撞:
// By specific tile indexes
layer.setCollision([1, 2, 3]);// By range (inclusive)
layer.setCollisionBetween(1, 50);// By tile property (set in Tiled's tileset editor)
layer.setCollisionByProperty({ collides: true });
// Supports arrays: { type: ['stone', 'lava'] }// By exclusion - collide on ALL tiles except these
layer.setCollisionByExclusion([-1, 0]); // -1 is empty, 0 is often background// From Tiled collision editor shapes
layer.setCollisionFromCollisionGroup();
所有位于 TilemapLayerBase 镜像方法 Tilemap 但不需要 layer 参数。在 Tilemap上,您可以传入图层引用或使用“当前图层”:
map.setLayer('Ground');
map.setCollision([1, 2, 3]); // Applies to current layer
// Or specify a layer explicitly:
map.setCollision([1, 2, 3], true, true, 'Ground');
物理集成(Arcade)
// Enable collisions between a sprite and a tilemap layer
this.physics.add.collider(player, groundLayer);// With a callback
this.physics.add.collider(player, groundLayer, (sprite, tile) => {
if (tile.index === 5) {
// Hit a special tile
}
});// Overlap detection instead of collision
this.physics.add.overlap(player, groundLayer, (sprite, tile) => {
// Player is overlapping this tile
});
该图层必须在其瓦片上启用了碰撞检测(通过 setCollision* 方法)设置碰撞属性,物理系统才能检测到这些瓦片。该图层本身具有 collisionCategory 和 collisionMask 属性用于碰撞过滤。
瓦片属性
可以在 Tiled 的贴图集编辑器中为贴图设置自定义属性:
// Access tile properties
const tile = layer.getTileAt(10, 5);
console.log(tile.properties.damage); // Custom property from Tiled
console.log(tile.properties.type); // Custom property from Tiled// Set collision based on custom properties
layer.setCollisionByProperty({ collides: true });
layer.setCollisionByProperty({ type: ['wall', 'rock'] });
贴图回调
// Callback by tile index - fires when physics body overlaps these tiles
map.setTileIndexCallback([5, 6, 7], (sprite, tile) => {
// Called for tiles with index 5, 6, or 7
console.log('Hit tile', tile.index, 'at', tile.x, tile.y);
}, this);// Callback by tile location - fires for tiles in a rectangular area
map.setTileLocationCallback(10, 10, 5, 5, (sprite, tile) => {
// Called for any tile in the 5x5 region starting at (10, 10)
}, this);// Per-tile callback
const tile = layer.getTileAt(10, 5);
tile.collisionCallback = (sprite, tile) => {
// Custom logic for this specific tile
};
图块回调要求物体与图层之间存在有效的物理碰撞体/重叠区域。
查询贴图
const tile = layer.getTileAt(10, 5); // By tile coords (or null)
const tile = layer.getTileAt(10, 5, true); // nonNull: Tile with index -1 instead of null
const tile = layer.getTileAtWorldXY(worldX, worldY); // By world coords
const exists = layer.hasTileAt(10, 5); // Boolean check// Region queries
const tiles = layer.getTilesWithin(0, 0, 10, 10); // Tile coord region
const tiles = layer.getTilesWithinWorldXY(x, y, w, h); // World coord region
const tiles = layer.getTilesWithinShape(circle); // Shape overlap// Functional queries
const water = layer.filterTiles(t => t.properties.type === 'water');
const spawn = layer.findTile(t => t.properties.isSpawn);
layer.forEachTile(t => { /* iterate all tiles */ });
运行时修改贴图
layer.putTileAt(5, 10, 10); // Place tile index 5 at (10, 10)
layer.putTileAtWorldXY(5, worldX, worldY); // Place by world coords
layer.putTilesAt([[1, 2], [3, 4]], 10, 10); // Place a 2x2 grid
layer.removeTileAt(10, 10); // Remove tile
layer.fill(1, 0, 0, 10, 10); // Fill 10x10 region with index 1
layer.replaceByIndex(5, 10); // Replace all index-5 with index-10
layer.copy(0, 0, 5, 5, 20, 20); // Copy 5x5 from (0,0) to (20,20)
layer.randomize(0, 0, 10, 10, [1, 2, 3, 4]); // Random tiles in region
layer.weightedRandomize([{ index: 1, weight: 4 }, { index: 2, weight: 1 }], 0, 0, 10, 10);
layer.shuffle(0, 0, 10, 10); // Shuffle tiles in region
坐标转换
const tileXY = layer.worldToTileXY(worldX, worldY); // World -> tile coords
const worldXY = layer.tileToWorldXY(tileX, tileY); // Tile -> world coords// Reuse a vector to avoid allocation
const vec = new Phaser.Math.Vector2();
layer.worldToTileXY(worldX, worldY, true, vec); // snapToFloor = true
对象图层(瓦片式)
瓦片式对象图层用于定义点、矩形和精灵的放置位置。请使用 createFromObjects 在 Tilemap:
// Create sprites from all objects on the 'Enemies' object layer
const enemies = map.createFromObjects('Enemies', {
gid: 26, // Match by tile GID
classType: Enemy // Custom class extending Sprite
});// Match by name
const coins = map.createFromObjects('Items', {
name: 'coin',
key: 'coin-texture',
frame: 0
});// Match by type
const spawns = map.createFromObjects('Spawns', {
type: 'player-spawn'
});// Access raw object layer data
const objectLayer = map.getObjectLayer('Enemies');
objectLayer.objects.forEach(obj => {
console.log(obj.name, obj.x, obj.y, obj.properties);
});
createFromObjects(layerName, config, useTileset) 配置选项: id, gid, name, type, classType (默认 Sprite), scene, container, key, frame, ignoreTileset.
动画贴图
贴图动画在 Tiled 的贴图集编辑器中定义,并会自动解析。 TilemapLayer 和 TilemapGPULayer 均支持动画贴图。 TilemapLayerBase 使用 ElapseTimer 通过 preUpdate.
等距、六边形和错位地图
// Isometric map
const map = this.add.tilemap('iso-map');
const tileset = map.addTilesetImage('iso-tiles', 'iso-img');
const layer = map.createLayer('Ground', tileset);// Get tile at world coords in isometric space
const tile = layer.getIsoTileAtWorldXY(worldX, worldY);// TilemapGPULayer does NOT support iso/hex/staggered - use TilemapLayer
地图的 orientation 属性由 Tiled 数据设定。坐标转换函数会根据方向自动选择。
API 快速参考
瓦片地图(数据容器——不进行渲染)
大多数瓦片查询/碰撞/操作方法同时存在于 Tilemap (带有额外的 layer 参数)和 TilemapLayerBase (无该参数)上均存在。建议直接在图层上调用。
TilemapLayerBase(渲染层——CPU 和 GPU)
碰撞:
setCollision(indexes), setCollisionBetween(start, stop), setCollisionByProperty(props), setCollisionByExclusion(indexes), setCollisionFromCollisionGroup(), setTileIndexCallback(indexes, cb, ctx), setTileLocationCallback(x, y, w, h, cb, ctx)
瓦片查询:
getTileAt(x, y, nonNull), getTileAtWorldXY(wx, wy, nonNull, cam), getTilesWithin(x, y, w, h, opts), getTilesWithinWorldXY(wx, wy, w, h, opts, cam), getTilesWithinShape(shape, opts, cam), hasTileAt(x, y), hasTileAtWorldXY(wx, wy, cam), filterTiles(cb), findTile(cb), forEachTile(cb)
瓦片操作:
putTileAt(tile, x, y), putTileAtWorldXY(tile, wx, wy), putTilesAt(arr, x, y), removeTileAt(x, y), fill(index, x, y, w, h), copy(sx, sy, w, h, dx, dy), randomize(x, y, w, h, indexes), weightedRandomize(weights, x, y, w, h), shuffle(x, y, w, h), swapByIndex(a, b), replaceByIndex(find, replace), createFromTiles(indexes, replacements, config)
坐标:
worldToTileXY(wx, wy, snap, vec, cam), tileToWorldXY(tx, ty, vec, cam)
TilemapGPULayer(附加)
瓦片属性
index (数字,-1 表示为空), x/y (贴图坐标), pixelX/pixelY (相对于图层的像素位置), width/height, properties (来自 Tiled 的对象), collideLeft/Right/Up/Down (布尔值), collisionCallback (函数), tint (数字), rotation (数字), alpha, flipX/flipY, physics (用于引擎数据的对象)
注意事项
-
贴图集名称必须与 Tiled 中的名称完全一致。
addTilesetImage的第一个参数是 Tiled 中定义的贴图集名称,而非 Phaser 的纹理键。如果两者不匹配,将返回null并触发控制台警告。 -
图层名称必须与 Tiled 中的名称完全一致。
createLayer该函数从 Tiled 中获取图层名称(或图层索引)。组内子图层名前会添加前缀'GroupName/LayerName'. -
每个图层只能创建一次。若调用
createLayer两次,将返回null并伴随警告。图层数据只能与一个图层游戏对象相关联。 -
setCollision必须在物理碰撞体生效前调用该方法。若未将瓦片标记为可碰撞,this.physics.add.collider()将穿透所有地砖。 -
TilemapGPULayer 仅支持正交投影。它不支持等距、六边形或错位地图。此外,每层仅支持一套贴图集。
-
TilemapGPULayer 需要手动重新生成纹理。在调用
putTileAt或其他编辑方法后,请调用generateLayerDataTexture(),否则更改将不会生效。 -
不支持“图像集合”类型的贴图集。Tiled 解析器要求贴图集中的所有贴图必须位于同一张图像中。导出 JSON 文件时必须包含嵌入式贴图集。
-
瓦片索引 -1 表示空瓦片。许多方法默认返回
null。请传递nonNull: true可获取一个包含index === -1。 -
insertNull在瓦片地图生成器中。创建瓦片地图时,insertNull: true会将null,而非存储索引为 -1 的 Tile 对象。这可为大型稀疏地图节省内存,但会阻止在空单元格中动态放置图块。 -
Tile 回调仅在物理系统处于活动状态时触发。
setTileIndexCallback并且setTileLocationCallback需要物理碰撞体,或者物体与图层之间存在重叠,才能触发。 -
图层位置和瓦片偏移量。如果
x且y未在createLayer中未指定,则默认采用在 Tiled 中定义的图层偏移量,而非 (0, 0)。
源文件映射
Tilemaps
Phaser Tilemaps render tile-based levels from Tiled JSON, CSV, or raw 2D arrays. A
Tilemapholds parsed map data and provides methods to add tilesets, create layers, set collision, and query tiles. Layers (TilemapLayerorTilemapGPULayer) are the Game Objects that actually render tiles. Phaser supports orthogonal, isometric, hexagonal, and staggered maps.
Key source paths: src/tilemaps/Tilemap.js, src/tilemaps/TilemapLayer.js, src/tilemaps/TilemapGPULayer.js, src/tilemaps/TilemapLayerBase.js, src/tilemaps/Tile.js, src/tilemaps/Tileset.js, src/tilemaps/TilemapFactory.js, src/tilemaps/components/, src/tilemaps/parsers/tiled/
Related skills: ../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md
Quick Start
class GameScene extends Phaser.Scene {
preload() {
// Load the Tiled JSON and the tileset image
this.load.tilemapTiledJSON('map', 'assets/level1.json');
this.load.image('tiles', 'assets/tilesheet.png');
} create() {
// Create the tilemap from cached JSON
const map = this.add.tilemap('map'); // Link the tileset image to the tileset name used in Tiled
const tileset = map.addTilesetImage('tilesheet', 'tiles'); // Create a layer - layerID must match the layer name in Tiled
const ground = map.createLayer('Ground', tileset); // Enable collision on specific tile indexes
ground.setCollision([1, 2, 3]);
}
}
The flow is always: load JSON + image, create tilemap, add tileset image, create layer(s), set collision.
Core Concepts
Tilemap vs Layer
A Tilemap is a data container, not a display object. It stores parsed map data (layers, tilesets, objects) and provides methods that operate on them. A TilemapLayer or TilemapGPULayer is the actual Game Object added to the display list that renders tiles.
const map = this.add.tilemap('map'); // Data container (not rendered)
const layer = map.createLayer('Ground', tileset); // Game Object (rendered)
this.add.tilemap(key) is a factory registered on GameObjectFactory. It delegates to ParseToTilemap which reads from the cache and returns a Tilemap instance.
Tilesets
A Tileset (src/tilemaps/Tileset.js) links a tileset name (from Tiled) to a loaded texture. It stores firstgid, tile dimensions, margin, and spacing.
// tilesetName: the name in Tiled's tileset panel
// key: the Phaser texture key (defaults to tilesetName if omitted)
const tileset = map.addTilesetImage('tilesetName', 'textureKey');// Override tile dimensions, margin, and spacing if needed
const tileset = map.addTilesetImage('name', 'key', 16, 16, 1, 2);
addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset) - If the tileset name already exists in the parsed map data, it updates the existing Tileset object with the texture. If not (non-Tiled maps), it creates a new Tileset.
Important: The Phaser Tiled parser does not support "Collection of Images" tilesets. All tiles must be in a single tileset image per tileset.
The Tile Class
Each cell in a layer is a Tile object (src/tilemaps/Tile.js). Key properties:
index- tile index in the tileset (-1 for empty)x,y- tile coordinates (in tiles, not pixels)pixelX,pixelY- pixel position relative to layer originwidth,height- tile size in pixelsproperties- custom properties from Tiled (object)collideLeft,collideRight,collideUp,collideDown- per-edge collision flagsfaceLeft,faceRight,faceTop,faceBottom- interesting face flags for collision optimizationcollisionCallback- per-tile collision callback functiontint- tint color value (default0xffffff)tintMode- tint blend mode (defaultTintModes.MULTIPLY)rotation- rotation anglephysics- object for physics-engine-specific data (e.g. bodies)alpha,visible,flipX,flipY- inherited from mixins
TilemapGPULayer (v4.0.0)
TilemapGPULayer is a high-performance WebGL-only alternative to TilemapLayer. It renders the entire layer as a single quad using a shader, making it almost entirely GPU-bound.
// Pass gpu: true as the 5th argument to createLayer
const layer = map.createLayer('Ground', tileset, 0, 0, true);
Capabilities:
- Single tileset per layer only (no multi-tileset)
- Max tilemap size: 4096x4096 tiles
- Max unique tile IDs: 2^23 (8,388,608)
- Supports tile flip and tile animation
- Orthographic maps only (no iso/hex/staggered)
- Smooth tile borders with LINEAR filtering (no seams)
- Sharp pixels with NEAREST filtering
Restrictions:
- Layer edits do not display automatically. Call
generateLayerDataTexture()after modifying tiles. - WebGL renderer only (no Canvas fallback)
- Cannot use multiple tilesets on a single layer
// If you edit tiles on a GPU layer, regenerate the data texture:
gpuLayer.putTileAt(5, 10, 10);
gpuLayer.generateLayerDataTexture();
TilemapLayerBase
Both TilemapLayer and TilemapGPULayer extend TilemapLayerBase (src/tilemaps/TilemapLayerBase.js), which extends GameObject. The base class provides all tile query, manipulation, and collision methods. It includes these component mixins: Alpha, BlendMode, ComputedSize, Depth, ElapseTimer, Flip, GetBounds, Lighting, Mask, Origin, RenderNodes, Transform, Visible, ScrollFactor, and Arcade Physics Collision.
Common Patterns
Creating from Tiled JSON
preload() {
this.load.tilemapTiledJSON('map', 'assets/map.json');
this.load.image('tiles', 'assets/tileset.png');
}create() {
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('TilesetNameInTiled', 'tiles');
const layer = map.createLayer('LayerNameInTiled', tileset);
}
The layerID passed to createLayer must match the layer name in Tiled exactly. Group layer children are flattened with a 'ParentGroup/Layer' naming convention.
Multiple Layers
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('terrain', 'terrain-img');const background = map.createLayer('Background', tileset);
const ground = map.createLayer('Ground', tileset);
const foreground = map.createLayer('Foreground', tileset);// Layers are rendered in creation order. Use depth for finer control:
foreground.setDepth(10);
A layer can use multiple tilesets (CPU layer only):
const tiles1 = map.addTilesetImage('terrain', 'terrain-img');
const tiles2 = map.addTilesetImage('objects', 'objects-img');
const layer = map.createLayer('Ground', [tiles1, tiles2]);
Creating a Blank Layer
const map = this.add.tilemap('map');
const tileset = map.addTilesetImage('terrain', 'terrain-img');// createBlankLayer(name, tileset, x, y, width, height, tileWidth, tileHeight)
const layer = map.createBlankLayer('dynamic', tileset, 0, 0, 50, 50, 32, 32);// Fill it with tiles
layer.fill(1); // Fill entire layer with tile index 1
layer.putTileAt(5, 10, 10); // Place tile index 5 at tile coord (10, 10)
Collision Setup
There are several ways to enable tile collision for Arcade Physics:
// By specific tile indexes
layer.setCollision([1, 2, 3]);// By range (inclusive)
layer.setCollisionBetween(1, 50);// By tile property (set in Tiled's tileset editor)
layer.setCollisionByProperty({ collides: true });
// Supports arrays: { type: ['stone', 'lava'] }// By exclusion - collide on ALL tiles except these
layer.setCollisionByExclusion([-1, 0]); // -1 is empty, 0 is often background// From Tiled collision editor shapes
layer.setCollisionFromCollisionGroup();
All collision methods on TilemapLayerBase mirror methods on Tilemap but don't require a layer parameter. On the Tilemap, you can pass a layer reference or use the "current layer":
map.setLayer('Ground');
map.setCollision([1, 2, 3]); // Applies to current layer
// Or specify a layer explicitly:
map.setCollision([1, 2, 3], true, true, 'Ground');
Physics Integration (Arcade)
// Enable collisions between a sprite and a tilemap layer
this.physics.add.collider(player, groundLayer);// With a callback
this.physics.add.collider(player, groundLayer, (sprite, tile) => {
if (tile.index === 5) {
// Hit a special tile
}
});// Overlap detection instead of collision
this.physics.add.overlap(player, groundLayer, (sprite, tile) => {
// Player is overlapping this tile
});
The layer must have collision set on its tiles (via setCollision* methods) for physics to detect them. The layer itself has collisionCategory and collisionMask properties for collision filtering.
Tile Properties
Tiles can have custom properties set in Tiled's tileset editor:
// Access tile properties
const tile = layer.getTileAt(10, 5);
console.log(tile.properties.damage); // Custom property from Tiled
console.log(tile.properties.type); // Custom property from Tiled// Set collision based on custom properties
layer.setCollisionByProperty({ collides: true });
layer.setCollisionByProperty({ type: ['wall', 'rock'] });
Tile Callbacks
// Callback by tile index - fires when physics body overlaps these tiles
map.setTileIndexCallback([5, 6, 7], (sprite, tile) => {
// Called for tiles with index 5, 6, or 7
console.log('Hit tile', tile.index, 'at', tile.x, tile.y);
}, this);// Callback by tile location - fires for tiles in a rectangular area
map.setTileLocationCallback(10, 10, 5, 5, (sprite, tile) => {
// Called for any tile in the 5x5 region starting at (10, 10)
}, this);// Per-tile callback
const tile = layer.getTileAt(10, 5);
tile.collisionCallback = (sprite, tile) => {
// Custom logic for this specific tile
};
Tile callbacks require an active physics collider/overlap between the body and the layer.
Querying Tiles
const tile = layer.getTileAt(10, 5); // By tile coords (or null)
const tile = layer.getTileAt(10, 5, true); // nonNull: Tile with index -1 instead of null
const tile = layer.getTileAtWorldXY(worldX, worldY); // By world coords
const exists = layer.hasTileAt(10, 5); // Boolean check// Region queries
const tiles = layer.getTilesWithin(0, 0, 10, 10); // Tile coord region
const tiles = layer.getTilesWithinWorldXY(x, y, w, h); // World coord region
const tiles = layer.getTilesWithinShape(circle); // Shape overlap// Functional queries
const water = layer.filterTiles(t => t.properties.type === 'water');
const spawn = layer.findTile(t => t.properties.isSpawn);
layer.forEachTile(t => { /* iterate all tiles */ });
Modifying Tiles at Runtime
layer.putTileAt(5, 10, 10); // Place tile index 5 at (10, 10)
layer.putTileAtWorldXY(5, worldX, worldY); // Place by world coords
layer.putTilesAt([[1, 2], [3, 4]], 10, 10); // Place a 2x2 grid
layer.removeTileAt(10, 10); // Remove tile
layer.fill(1, 0, 0, 10, 10); // Fill 10x10 region with index 1
layer.replaceByIndex(5, 10); // Replace all index-5 with index-10
layer.copy(0, 0, 5, 5, 20, 20); // Copy 5x5 from (0,0) to (20,20)
layer.randomize(0, 0, 10, 10, [1, 2, 3, 4]); // Random tiles in region
layer.weightedRandomize([{ index: 1, weight: 4 }, { index: 2, weight: 1 }], 0, 0, 10, 10);
layer.shuffle(0, 0, 10, 10); // Shuffle tiles in region
Coordinate Conversion
const tileXY = layer.worldToTileXY(worldX, worldY); // World -> tile coords
const worldXY = layer.tileToWorldXY(tileX, tileY); // Tile -> world coords// Reuse a vector to avoid allocation
const vec = new Phaser.Math.Vector2();
layer.worldToTileXY(worldX, worldY, true, vec); // snapToFloor = true
Object Layers (Tiled)
Tiled object layers define points, rectangles, and sprite placement. Use createFromObjects on the Tilemap:
// Create sprites from all objects on the 'Enemies' object layer
const enemies = map.createFromObjects('Enemies', {
gid: 26, // Match by tile GID
classType: Enemy // Custom class extending Sprite
});// Match by name
const coins = map.createFromObjects('Items', {
name: 'coin',
key: 'coin-texture',
frame: 0
});// Match by type
const spawns = map.createFromObjects('Spawns', {
type: 'player-spawn'
});// Access raw object layer data
const objectLayer = map.getObjectLayer('Enemies');
objectLayer.objects.forEach(obj => {
console.log(obj.name, obj.x, obj.y, obj.properties);
});
createFromObjects(layerName, config, useTileset) config options: id, gid, name, type, classType (default Sprite), scene, container, key, frame, ignoreTileset.
Animated Tiles
Tile animations are defined in Tiled's tileset editor and parsed automatically. Both TilemapLayer and TilemapGPULayer support animated tiles. The TilemapLayerBase uses ElapseTimer to track animation time via preUpdate.
Isometric, Hexagonal, and Staggered Maps
// Isometric map
const map = this.add.tilemap('iso-map');
const tileset = map.addTilesetImage('iso-tiles', 'iso-img');
const layer = map.createLayer('Ground', tileset);// Get tile at world coords in isometric space
const tile = layer.getIsoTileAtWorldXY(worldX, worldY);// TilemapGPULayer does NOT support iso/hex/staggered - use TilemapLayer
The map orientation property is set from Tiled data. Coordinate conversion functions are automatically selected based on orientation.
API Quick Reference
Tilemap (data container - not rendered)
Most tile query/collision/manipulation methods exist on both Tilemap (with extra layer param) and TilemapLayerBase (without). Prefer calling on the layer directly.
TilemapLayerBase (rendered layer - CPU and GPU)
Collision:
setCollision(indexes), setCollisionBetween(start, stop), setCollisionByProperty(props), setCollisionByExclusion(indexes), setCollisionFromCollisionGroup(), setTileIndexCallback(indexes, cb, ctx), setTileLocationCallback(x, y, w, h, cb, ctx)
Tile queries:
getTileAt(x, y, nonNull), getTileAtWorldXY(wx, wy, nonNull, cam), getTilesWithin(x, y, w, h, opts), getTilesWithinWorldXY(wx, wy, w, h, opts, cam), getTilesWithinShape(shape, opts, cam), hasTileAt(x, y), hasTileAtWorldXY(wx, wy, cam), filterTiles(cb), findTile(cb), forEachTile(cb)
Tile manipulation:
putTileAt(tile, x, y), putTileAtWorldXY(tile, wx, wy), putTilesAt(arr, x, y), removeTileAt(x, y), fill(index, x, y, w, h), copy(sx, sy, w, h, dx, dy), randomize(x, y, w, h, indexes), weightedRandomize(weights, x, y, w, h), shuffle(x, y, w, h), swapByIndex(a, b), replaceByIndex(find, replace), createFromTiles(indexes, replacements, config)
Coordinates:
worldToTileXY(wx, wy, snap, vec, cam), tileToWorldXY(tx, ty, vec, cam)
TilemapGPULayer (additional)
Tile Properties
index (number, -1=empty), x/y (tile coords), pixelX/pixelY (pixel pos relative to layer), width/height, properties (object from Tiled), collideLeft/Right/Up/Down (boolean), collisionCallback (function), tint (number), rotation (number), alpha, flipX/flipY, physics (object for engine data)
Gotchas
-
Tileset name must match Tiled exactly. The first argument to
addTilesetImageis the tileset name as defined in Tiled, not the Phaser texture key. If they don't match, you getnullback and a console warning. -
Layer name must match Tiled exactly.
createLayertakes the layer name from Tiled (or layer index). Group layer children are prefixed with'GroupName/LayerName'. -
Each layer can only be created once. Calling
createLayerwith the same layer ID twice returnsnullwith a warning. The layer data can only be associated with one layer Game Object. -
setCollisionmust be called before physics colliders work. Without marking tiles as collidable,this.physics.add.collider()will pass through all tiles. -
TilemapGPULayer is orthographic only. It does not support isometric, hexagonal, or staggered maps. It also only supports a single tileset per layer.
-
TilemapGPULayer requires manual texture regeneration. After calling
putTileAtor other edit methods, callgenerateLayerDataTexture()or the changes won't appear. -
"Collection of Images" tilesets are not supported. The Tiled parser requires all tiles in a tileset to be in a single image. Embedded tilesets in the exported JSON are required.
-
Tile index -1 means empty. Many methods return
nullfor empty tiles by default. PassnonNull: trueto get a Tile object withindex === -1instead. -
insertNullin tilemap factory. When creating a tilemap,insertNull: truestoresnullfor empty tiles instead of Tile objects with index -1. Saves memory for large sparse maps but prevents dynamic tile placement in empty cells. -
Tile callbacks only fire with active physics.
setTileIndexCallbackandsetTileLocationCallbackrequire a physics collider or overlap between the body and the layer to trigger. -
Layer position and Tiled offset. If
xandyare not specified increateLayer, they default to the layer offset defined in Tiled, not (0, 0).





首页
