tilemaps
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTilemaps
瓦片地图(Tilemaps)
Phaser Tilemaps render tile-based levels from Tiled JSON, CSV, or raw 2D arrays. Aholds parsed map data and provides methods to add tilesets, create layers, set collision, and query tiles. Layers (TilemaporTilemapLayer) are the Game Objects that actually render tiles. Phaser supports orthogonal, isometric, hexagonal, and staggered maps.TilemapGPULayer
Key source paths: , , , , , , , ,
Related skills: ../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md
src/tilemaps/Tilemap.jssrc/tilemaps/TilemapLayer.jssrc/tilemaps/TilemapGPULayer.jssrc/tilemaps/TilemapLayerBase.jssrc/tilemaps/Tile.jssrc/tilemaps/Tileset.jssrc/tilemaps/TilemapFactory.jssrc/tilemaps/components/src/tilemaps/parsers/tiled/Phaser Tilemaps 可从Tiled JSON、CSV或原始二维数组渲染基于瓦片的关卡。存储解析后的地图数据,并提供添加瓦片集、创建图层、设置碰撞以及查询瓦片的方法。图层(Tilemap或TilemapLayer)是实际渲染瓦片的游戏对象。Phaser 支持正交、等距、六边形和交错式地图。TilemapGPULayer
核心源码路径: , , , , , , , ,
相关技能: ../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md
src/tilemaps/Tilemap.jssrc/tilemaps/TilemapLayer.jssrc/tilemaps/TilemapGPULayer.jssrc/tilemaps/TilemapLayerBase.jssrc/tilemaps/Tile.jssrc/tilemaps/Tileset.jssrc/tilemaps/TilemapFactory.jssrc/tilemaps/components/src/tilemaps/parsers/tiled/Quick Start
快速入门
js
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.
js
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 + 图片,创建tilemap,添加瓦片集图片,创建图层,设置碰撞。
Core Concepts
核心概念
Tilemap vs Layer
Tilemap 与图层
A is a data container, not a display object. It stores parsed map data (layers, tilesets, objects) and provides methods that operate on them. A or is the actual Game Object added to the display list that renders tiles.
TilemapTilemapLayerTilemapGPULayerjs
const map = this.add.tilemap('map'); // Data container (not rendered)
const layer = map.createLayer('Ground', tileset); // Game Object (rendered)this.add.tilemap(key)GameObjectFactoryParseToTilemapTilemapTilemapTilemapLayerTilemapGPULayerjs
const map = this.add.tilemap('map'); // 数据容器(不渲染)
const layer = map.createLayer('Ground', tileset); // 游戏对象(会渲染)this.add.tilemap(key)GameObjectFactoryParseToTilemapTilemapTilesets
瓦片集(Tilesets)
A () links a tileset name (from Tiled) to a loaded texture. It stores , tile dimensions, margin, and spacing.
Tilesetsrc/tilemaps/Tileset.jsfirstgidjs
// 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)Important: The Phaser Tiled parser does not support "Collection of Images" tilesets. All tiles must be in a single tileset image per tileset.
Tilesetsrc/tilemaps/Tileset.jsfirstgidjs
// tilesetName: Tiled瓦片集面板中的名称
// key: Phaser纹理键(如果省略则默认与tilesetName相同)
const tileset = map.addTilesetImage('tilesetName', 'textureKey');
// 如有需要,覆盖瓦片尺寸、边距和间距
const tileset = map.addTilesetImage('name', 'key', 16, 16, 1, 2);addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset)重要提示: Phaser的Tiled解析器不支持“图片集合”类型的瓦片集。每个瓦片集的所有瓦片必须在单个瓦片集图片中。
The Tile Class
Tile类
Each cell in a layer is a object (). Key properties:
Tilesrc/tilemaps/Tile.js- - tile index in the tileset (-1 for empty)
index - ,
x- tile coordinates (in tiles, not pixels)y - ,
pixelX- pixel position relative to layer originpixelY - ,
width- tile size in pixelsheight - - custom properties from Tiled (object)
properties - ,
collideLeft,collideRight,collideUp- per-edge collision flagscollideDown - ,
faceLeft,faceRight,faceTop- interesting face flags for collision optimizationfaceBottom - - per-tile collision callback function
collisionCallback - - tint color value (default
tint)0xffffff - - tint blend mode (default
tintMode)TintModes.MULTIPLY - - rotation angle
rotation - - object for physics-engine-specific data (e.g. bodies)
physics - ,
alpha,visible,flipX- inherited from mixinsflipY
图层中的每个单元格都是一个 对象()。关键属性:
Tilesrc/tilemaps/Tile.js- - 瓦片在瓦片集中的索引(-1表示空)
index - ,
x- 瓦片坐标(以瓦片为单位,而非像素)y - ,
pixelX- 相对于图层原点的像素位置pixelY - ,
width- 瓦片的像素尺寸height - - 来自Tiled的自定义属性(对象)
properties - ,
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(v4.0.0)
TilemapGPULayerTilemapLayerjs
// 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 after modifying tiles.
generateLayerDataTexture() - WebGL renderer only (no Canvas fallback)
- Cannot use multiple tilesets on a single layer
js
// If you edit tiles on a GPU layer, regenerate the data texture:
gpuLayer.putTileAt(5, 10, 10);
gpuLayer.generateLayerDataTexture();TilemapGPULayerTilemapLayerjs
// 在createLayer的第5个参数中传入gpu: true
const layer = map.createLayer('Ground', tileset, 0, 0, true);功能:
- 每个图层仅支持单个瓦片集(不支持多瓦片集)
- 最大瓦片地图尺寸:4096x4096瓦片
- 最大唯一瓦片ID:2^23(8,388,608)
- 支持瓦片翻转和瓦片动画
- 仅支持正交地图(不支持等距/六边形/交错式)
- 使用LINEAR过滤实现平滑瓦片边框(无接缝)
- 使用NEAREST过滤实现清晰像素
限制:
- 图层编辑不会自动显示。修改瓦片后需调用 。
generateLayerDataTexture() - 仅支持WebGL渲染器(无Canvas回退)
- 单个图层不能使用多个瓦片集
js
// 如果在GPU图层上编辑瓦片,重新生成数据纹理:
gpuLayer.putTileAt(5, 10, 10);
gpuLayer.generateLayerDataTexture();TilemapLayerBase
TilemapLayerBase
Both and extend (), which extends . 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.
TilemapLayerTilemapGPULayerTilemapLayerBasesrc/tilemaps/TilemapLayerBase.jsGameObjectTilemapLayerTilemapGPULayerTilemapLayerBasesrc/tilemaps/TilemapLayerBase.jsGameObjectCommon Patterns
常见模式
Creating from Tiled JSON
从Tiled JSON创建
js
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 passed to must match the layer name in Tiled exactly. Group layer children are flattened with a naming convention.
layerIDcreateLayer'ParentGroup/Layer'js
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);
}传递给 的 必须与Tiled中的图层名称完全匹配。组图层的子图层会以 的命名规则展平。
createLayerlayerID'ParentGroup/Layer'Multiple Layers
多个图层
js
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):
js
const tiles1 = map.addTilesetImage('terrain', 'terrain-img');
const tiles2 = map.addTilesetImage('objects', 'objects-img');
const layer = map.createLayer('Ground', [tiles1, tiles2]);js
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);
// 图层按创建顺序渲染。使用depth进行更精细的控制:
foreground.setDepth(10);一个图层可以使用多个瓦片集(仅CPU图层):
js
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
创建空白图层
js
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)js
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);
// 用瓦片填充图层
layer.fill(1); // 用索引为1的瓦片填充整个图层
layer.putTileAt(5, 10, 10); // 在瓦片坐标(10,10)处放置索引为5的瓦片Collision Setup
碰撞设置
There are several ways to enable tile collision for Arcade Physics:
js
// 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 mirror methods on but don't require a parameter. On the , you can pass a layer reference or use the "current layer":
TilemapLayerBaseTilemaplayerTilemapjs
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 Physics启用瓦片碰撞:
js
// 通过特定瓦片索引
layer.setCollision([1, 2, 3]);
// 通过范围(包含两端)
layer.setCollisionBetween(1, 50);
// 通过瓦片属性(在Tiled的瓦片集编辑器中设置)
layer.setCollisionByProperty({ collides: true });
// 支持数组:{ type: ['stone', 'lava'] }
// 通过排除法 - 除这些瓦片外,所有瓦片都启用碰撞
layer.setCollisionByExclusion([-1, 0]); // -1表示空,0通常是背景
// 从Tiled碰撞编辑器形状设置
layer.setCollisionFromCollisionGroup();TilemapLayerBaseTilemaplayerTilemapjs
map.setLayer('Ground');
map.setCollision([1, 2, 3]); // 应用于当前图层
// 或者显式指定图层:
map.setCollision([1, 2, 3], true, true, 'Ground');Physics Integration (Arcade)
物理集成(Arcade)
js
// 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 methods) for physics to detect them. The layer itself has and properties for collision filtering.
setCollision*collisionCategorycollisionMaskjs
// 启用精灵与瓦片地图图层之间的碰撞
this.physics.add.collider(player, groundLayer);
// 带回调函数
this.physics.add.collider(player, groundLayer, (sprite, tile) => {
if (tile.index === 5) {
// 碰到了特殊瓦片
}
});
// 重叠检测而非碰撞
this.physics.add.overlap(player, groundLayer, (sprite, tile) => {
// 玩家正在与该瓦片重叠
});图层必须在其瓦片上设置碰撞(通过 方法),物理引擎才能检测到它们。图层本身具有 和 属性用于碰撞过滤。
setCollision*collisionCategorycollisionMaskTile Properties
瓦片属性
Tiles can have custom properties set in Tiled's tileset editor:
js
// 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'] });瓦片可以在Tiled的瓦片集编辑器中设置自定义属性:
js
// 访问瓦片属性
const tile = layer.getTileAt(10, 5);
console.log(tile.properties.damage); // 来自Tiled的自定义属性
console.log(tile.properties.type); // 来自Tiled的自定义属性
// 根据自定义属性设置碰撞
layer.setCollisionByProperty({ collides: true });
layer.setCollisionByProperty({ type: ['wall', 'rock'] });Tile Callbacks
瓦片回调
js
// 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.
js
// 按瓦片索引设置回调 - 当物理刚体与这些瓦片重叠时触发
map.setTileIndexCallback([5, 6, 7], (sprite, tile) => {
// 当碰到索引为5、6或7的瓦片时调用
console.log('Hit tile', tile.index, 'at', tile.x, tile.y);
}, this);
// 按瓦片位置设置回调 - 针对矩形区域内的瓦片触发
map.setTileLocationCallback(10, 10, 5, 5, (sprite, tile) => {
// 针对从(10,10)开始的5x5区域内的任何瓦片调用
}, this);
// 单个瓦片的回调
const tile = layer.getTileAt(10, 5);
tile.collisionCallback = (sprite, tile) => {
// 该特定瓦片的自定义逻辑
};瓦片回调需要刚体与图层之间存在活跃的物理碰撞器/重叠检测才能触发。
Querying Tiles
查询瓦片
js
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 */ });js
const tile = layer.getTileAt(10, 5); // 通过瓦片坐标获取(或null)
const tile = layer.getTileAt(10, 5, true); // nonNull: 返回index为-1的Tile对象而非null
const tile = layer.getTileAtWorldXY(worldX, worldY); // 通过世界坐标获取
const exists = layer.hasTileAt(10, 5); // 布尔值检查是否存在
// 区域查询
const tiles = layer.getTilesWithin(0, 0, 10, 10); // 瓦片坐标区域
const tiles = layer.getTilesWithinWorldXY(x, y, w, h); // 世界坐标区域
const tiles = layer.getTilesWithinShape(circle); // 形状重叠区域
// 函数式查询
const water = layer.filterTiles(t => t.properties.type === 'water');
const spawn = layer.findTile(t => t.properties.isSpawn);
layer.forEachTile(t => { /* 遍历所有瓦片 */ });Modifying Tiles at Runtime
运行时修改瓦片
js
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 regionjs
layer.putTileAt(5, 10, 10); // 在(10,10)处放置索引为5的瓦片
layer.putTileAtWorldXY(5, worldX, worldY); // 通过世界坐标放置瓦片
layer.putTilesAt([[1, 2], [3, 4]], 10, 10); // 在(10,10)处放置2x2网格的瓦片
layer.removeTileAt(10, 10); // 移除(10,10)处的瓦片
layer.fill(1, 0, 0, 10, 10); // 用索引为1的瓦片填充0,0开始的10x10区域
layer.replaceByIndex(5, 10); // 将所有索引为5的瓦片替换为索引为10的瓦片
layer.copy(0, 0, 5, 5, 20, 20); // 将0,0开始的5x5区域复制到20,20处
layer.randomize(0, 0, 10, 10, [1, 2, 3, 4]); // 在0,0开始的10x10区域内随机放置瓦片
layer.weightedRandomize([{ index: 1, weight: 4 }, { index: 2, weight: 1 }], 0, 0, 10, 10);
layer.shuffle(0, 0, 10, 10); // 打乱0,0开始的10x10区域内的瓦片Coordinate Conversion
坐标转换
js
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 = truejs
const tileXY = layer.worldToTileXY(worldX, worldY); // 世界坐标 -> 瓦片坐标
const worldXY = layer.tileToWorldXY(tileX, tileY); // 瓦片坐标 -> 世界坐标
// 重用向量以避免内存分配
const vec = new Phaser.Math.Vector2();
layer.worldToTileXY(worldX, worldY, true, vec); // snapToFloor = trueObject Layers (Tiled)
对象图层(Tiled)
Tiled object layers define points, rectangles, and sprite placement. Use on the :
createFromObjectsTilemapjs
// 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)idgidnametypeclassTypeSpritescenecontainerkeyframeignoreTilesetTiled对象图层定义点、矩形和精灵位置。使用 上的 方法:
TilemapcreateFromObjectsjs
// 从'Enemies'对象图层的所有对象创建精灵
const enemies = map.createFromObjects('Enemies', {
gid: 26, // 按瓦片GID匹配
classType: Enemy // 继承自Sprite的自定义类
});
// 按名称匹配
const coins = map.createFromObjects('Items', {
name: 'coin',
key: 'coin-texture',
frame: 0
});
// 按类型匹配
const spawns = map.createFromObjects('Spawns', {
type: 'player-spawn'
});
// 访问原始对象图层数据
const objectLayer = map.getObjectLayer('Enemies');
objectLayer.objects.forEach(obj => {
console.log(obj.name, obj.x, obj.y, obj.properties);
});createFromObjects(layerName, config, useTileset)idgidnametypeclassTypeSpritescenecontainerkeyframeignoreTilesetAnimated Tiles
动画瓦片
Tile animations are defined in Tiled's tileset editor and parsed automatically. Both and support animated tiles. The uses to track animation time via .
TilemapLayerTilemapGPULayerTilemapLayerBaseElapseTimerpreUpdate瓦片动画在Tiled的瓦片集编辑器中定义,并自动解析。 和 都支持动画瓦片。 使用 通过 跟踪动画时间。
TilemapLayerTilemapGPULayerTilemapLayerBaseElapseTimerpreUpdateIsometric, Hexagonal, and Staggered Maps
等距、六边形和交错式地图
js
// 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 TilemapLayerThe map property is set from Tiled data. Coordinate conversion functions are automatically selected based on orientation.
orientationjs
// 等距地图
const map = this.add.tilemap('iso-map');
const tileset = map.addTilesetImage('iso-tiles', 'iso-img');
const layer = map.createLayer('Ground', tileset);
// 在等距空间中通过世界坐标获取瓦片
const tile = layer.getIsoTileAtWorldXY(worldX, worldY);
// TilemapGPULayer 不支持等距/六边形/交错式地图 - 使用TilemapLayer地图的 属性由Tiled数据设置。坐标转换函数会根据方向自动选择。
orientationAPI Quick Reference
API快速参考
Tilemap (data container - not rendered)
Tilemap(数据容器 - 不渲染)
| Method | Description |
|---|---|
| Link tileset name to texture |
| Create layer ( |
| Create empty layer for procedural maps |
| Convert Tiled objects to Sprites |
| Get raw object layer data |
| Set current active layer for shorthand methods |
Most tile query/collision/manipulation methods exist on both (with extra param) and (without). Prefer calling on the layer directly.
TilemaplayerTilemapLayerBase| 方法 | 描述 |
|---|---|
| 将瓦片集名称链接到纹理 |
| 创建图层( |
| 创建空图层用于程序化地图 |
| 将Tiled对象转换为Sprites |
| 获取原始对象图层数据 |
| 设置当前活动图层以使用简写方法 |
大多数瓦片查询/碰撞/操作方法同时存在于 (需额外 参数)和 (无需参数)上。建议直接在图层上调用。
TilemaplayerTilemapLayerBaseTilemapLayerBase (rendered layer - CPU and GPU)
TilemapLayerBase(渲染图层 - CPU和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)碰撞:
, , , , , ,
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 (additional)
TilemapGPULayer(额外方法)
| Method | Description |
|---|---|
| Regenerate GPU texture after tile edits |
| 方法 | 描述 |
|---|---|
| 瓦片编辑后重新生成GPU纹理 |
Tile Properties
瓦片属性
indexxypixelXpixelYwidthheightpropertiescollideLeftRightUpDowncollisionCallbacktintrotationalphaflipXflipYphysicsindexxypixelXpixelYwidthheightpropertiescollideLeftRightUpDowncollisionCallbacktintrotationalphaflipXflipYphysicsGotchas
注意事项
-
Tileset name must match Tiled exactly. The first argument tois the tileset name as defined in Tiled, not the Phaser texture key. If they don't match, you get
addTilesetImageback and a console warning.null -
Layer name must match Tiled exactly.takes the layer name from Tiled (or layer index). Group layer children are prefixed with
createLayer.'GroupName/LayerName' -
Each layer can only be created once. Callingwith the same layer ID twice returns
createLayerwith a warning. The layer data can only be associated with one layer Game Object.null -
must be called before physics colliders work. Without marking tiles as collidable,
setCollisionwill pass through all tiles.this.physics.add.collider() -
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 callingor other edit methods, call
putTileAtor the changes won't appear.generateLayerDataTexture() -
"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 returnfor empty tiles by default. Pass
nullto get a Tile object withnonNull: trueinstead.index === -1 -
in tilemap factory. When creating a tilemap,
insertNullstoresinsertNull: truefor empty tiles instead of Tile objects with index -1. Saves memory for large sparse maps but prevents dynamic tile placement in empty cells.null -
Tile callbacks only fire with active physics.and
setTileIndexCallbackrequire a physics collider or overlap between the body and the layer to trigger.setTileLocationCallback -
Layer position and Tiled offset. Ifand
xare not specified iny, they default to the layer offset defined in Tiled, not (0, 0).createLayer
-
瓦片集名称必须与Tiled完全匹配。的第一个参数是Tiled中定义的瓦片集名称,而非Phaser纹理键。如果不匹配,会返回
addTilesetImage并在控制台输出警告。null -
图层名称必须与Tiled完全匹配。接受Tiled中的图层名称(或图层索引)。组图层的子图层会以
createLayer为前缀。'GroupName/LayerName' -
每个图层只能创建一次。 使用相同的图层ID调用两次会返回
createLayer并输出警告。图层数据只能关联到一个图层游戏对象。null -
必须先调用,物理碰撞器才能生效。 如果未将瓦片标记为可碰撞,
setCollision会穿过所有瓦片。this.physics.add.collider() -
TilemapGPULayer仅支持正交地图。 它不支持等距、六边形或交错式地图。同时每个图层仅支持单个瓦片集。
-
TilemapGPULayer需要手动重新生成纹理。 调用或其他编辑方法后,需调用
putTileAt,否则更改不会显示。generateLayerDataTexture() -
不支持“图片集合”类型的瓦片集。 Tiled解析器要求每个瓦片集的所有瓦片都在单个图片中。导出的JSON中需要包含嵌入的瓦片集。
-
瓦片索引-1表示空。 默认情况下,许多方法会为空瓦片返回。传递
null可获取nonNull: true的Tile对象。index === -1 -
tilemap工厂中的。 创建tilemap时,
insertNull会为空瓦片存储insertNull: true,而非index为-1的Tile对象。可为大型稀疏地图节省内存,但会阻止在空单元格中放置动态瓦片。null -
瓦片回调仅在物理活跃时触发。和
setTileIndexCallback需要刚体与图层之间存在物理碰撞器或重叠检测才能触发。setTileLocationCallback -
图层位置与Tiled偏移。 如果在中未指定
createLayer和x,它们默认使用Tiled中定义的图层偏移,而非(0, 0)。y
Source File Map
源码文件映射
| File | Purpose |
|---|---|
| Main data container with all map-level methods |
| Registers |
| Shared base for CPU and GPU layers (extends GameObject) |
| CPU-rendered layer (multi-tileset, all orientations) |
| GPU-accelerated layer (v4, WebGL, orthographic, single tileset) |
| Individual tile data (index, position, collision, properties) |
| Tileset data (name, firstgid, dimensions, image) |
| Pure functions: |
| Tiled JSON parsers: |
| Orchestrates parsing and Tilemap creation |
| Layer data structure |
| 文件 | 用途 |
|---|---|
| 主数据容器,包含所有地图级方法 |
| 在GameObjectFactory上注册 |
| CPU和GPU图层的共享基类(继承自GameObject) |
| CPU渲染的图层(支持多瓦片集、所有方向) |
| GPU加速图层(v4版本,WebGL,正交,单瓦片集) |
| 单个瓦片的数据(索引、位置、碰撞、属性) |
| 瓦片集数据(名称、firstgid、尺寸、图片) |
| 纯函数: |
| Tiled JSON解析器: |
| 协调解析和Tilemap创建 |
| 图层数据结构 |