godot-tilemap

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Godot TileMap (4.3+ TileMapLayer)

Godot TileMap(4.3+ TileMapLayer)

Author tile-based levels with
TileMapLayer
+
TileSet
, add per-tile collision and custom data, autotile with terrains, and manipulate cells at runtime. Targets Godot 4.3+, where
TileMapLayer
replaces the now-deprecated
TileMap
node.
使用
TileMapLayer
+
TileSet
制作基于瓦片的关卡,添加逐瓦片碰撞与自定义数据,通过地形实现自动瓦片,并在运行时操作单元格。本内容针对**Godot 4.3+**版本,其中
TileMapLayer
已取代现已弃用的
TileMap
节点。

When to use

适用场景

  • Use when designing 2D levels from a tile grid, configuring a
    TileSet
    (collision, navigation, custom data, terrains), or reading/writing tiles from code.
  • Use when migrating a
    TileMap
    node (single node, many layers) to multiple
    TileMapLayer
    nodes (one layer each).
When not to use: moving the player across the tiles →
godot-2d-movement
; general physics bodies/raycasts →
godot-physics
; procedural map generation algorithms →
procedural-gen
; level design practice →
level-design
.
  • 适用于从瓦片网格设计2D关卡、配置
    TileSet
    (碰撞、导航、自定义数据、地形),或通过代码读写瓦片的场景。
  • 适用于将单个多层的
    TileMap
    节点迁移为多个单层
    TileMapLayer
    节点的场景。
不适用场景: 让玩家在瓦片上移动 →
godot-2d-movement
;通用物理体/射线检测 →
godot-physics
;程序化地图生成算法 →
procedural-gen
;关卡设计实践 →
level-design

Core workflow

核心工作流程

  1. Add a
    TileMapLayer
    node
    (one per visual/logical layer: background, walls, foreground). Each holds exactly one layer of tiles.
  2. Create or assign a
    TileSet
    on the layer's
    tile_set
    property. Add an atlas source (a texture sliced into tiles) in the TileSet editor. Save the TileSet as an external
    .tres
    so multiple layers/levels reuse it.
  3. Add tile data in the TileSet editor: physics layers (collision polygons), navigation layers, occlusion, and custom data layers (typed per-tile values like
    damage
    or
    is_ladder
    ).
  4. Paint in the TileMap bottom panel (Paint/Line/Rectangle/Bucket). For self- connecting tiles, define a terrain set and paint with Connect/Path mode.
  5. Enable per-layer collision/navigation via the layer's
    collision_enabled
    /
    navigation_enabled
    properties.
  6. Read/write from code with
    local_to_map
    ,
    set_cell
    ,
    get_cell_source_id
    , and
    get_cell_tile_data(...).get_custom_data(...)
    .
  1. 添加
    TileMapLayer
    节点
    (每个视觉/逻辑图层对应一个节点:背景、墙体、前景)。每个节点仅包含一层瓦片。
  2. **创建或分配
    TileSet
    **至图层的
    tile_set
    属性。在TileSet编辑器中添加图集资源(将一张纹理切片为瓦片)。将TileSet保存为外部
    .tres
    文件,以便多个图层/关卡复用。
  3. 在TileSet编辑器中添加瓦片数据:物理图层(碰撞多边形)、导航图层、遮挡,以及自定义数据图层(逐瓦片的类型化值,如
    damage
    is_ladder
    )。
  4. 在TileMap底部面板绘制(画笔/直线/矩形/桶填充工具)。对于自动连接的瓦片,定义地形集并使用连接/路径模式绘制。
  5. 通过图层的
    collision_enabled
    /
    navigation_enabled
    属性启用逐图层碰撞/导航
  6. 通过代码读写,使用
    local_to_map
    set_cell
    get_cell_source_id
    get_cell_tile_data(...).get_custom_data(...)
    方法。

Patterns

实践模式

1. Convert mouse position to a cell and read its custom data

1. 将鼠标位置转换为单元格并读取其自定义数据

gdscript
extends TileMapLayer

func _unhandled_input(event: InputEvent) -> void:
    if event is InputEventMouseButton and event.pressed:
        # local_to_map expects local coords; convert from global first.
        var cell := local_to_map(to_local(event.position))
        var data := get_cell_tile_data(cell)   # TileData or null
        if data:
            var dmg: int = data.get_custom_data("damage")  # custom data layer
            print("Cell %s deals %d damage" % [cell, dmg])
gdscript
extends TileMapLayer

func _unhandled_input(event: InputEvent) -> void:
    if event is InputEventMouseButton and event.pressed:
        # local_to_map需要本地坐标;先将全局坐标转换为本地坐标。
        var cell := local_to_map(to_local(event.position))
        var data := get_cell_tile_data(cell)   # TileData或null
        if data:
            var dmg: int = data.get_custom_data("damage")  # 自定义数据图层
            print("Cell %s deals %d damage" % [cell, dmg])

2. Place and erase tiles at runtime

2. 在运行时放置与删除瓦片

gdscript
undefined
gdscript
undefined

set_cell(coords, source_id, atlas_coords, alternative_tile = 0)

set_cell(coords, source_id, atlas_coords, alternative_tile = 0)

func place_wall(cell: Vector2i) -> void: set_cell(cell, 0, Vector2i(2, 1)) # source 0, atlas tile at column 2, row 1
func dig(cell: Vector2i) -> void: erase_cell(cell) # same as set_cell(cell, -1)
func clear_level() -> void: clear() # remove every tile on this layer
undefined
func place_wall(cell: Vector2i) -> void: set_cell(cell, 0, Vector2i(2, 1)) # 资源ID为0,图集瓦片位于第2列第1行
func dig(cell: Vector2i) -> void: erase_cell(cell) # 等同于set_cell(cell, -1)
func clear_level() -> void: clear() # 删除本图层的所有瓦片
undefined

3. Autotiling a region with a terrain set

3. 使用地形集自动瓦片填充区域

gdscript
undefined
gdscript
undefined

Paint a filled area with terrain
terrain
of terrain set
terrain_set
;

使用地形集
terrain_set
中的
terrain
地形填充指定区域;

Godot picks the correct edge/corner tiles to connect them.

Godot会自动选择正确的边缘/拐角瓦片实现连接。

func fill_with_grass(cells: Array[Vector2i]) -> void: var terrain_set := 0 var grass_terrain := 0 set_cells_terrain_connect(cells, terrain_set, grass_terrain, true)
undefined
func fill_with_grass(cells: Array[Vector2i]) -> void: var terrain_set := 0 var grass_terrain := 0 set_cells_terrain_connect(cells, terrain_set, grass_terrain, true)
undefined

4. Iterate placed tiles (e.g. find all spawn tiles)

4. 遍历已放置的瓦片(例如查找所有出生点瓦片)

gdscript
func find_spawns() -> Array[Vector2i]:
    var spawns: Array[Vector2i] = []
    for cell in get_used_cells():
        var data := get_cell_tile_data(cell)
        if data and data.get_custom_data("is_spawn"):
            spawns.append(cell)
    return spawns
gdscript
func find_spawns() -> Array[Vector2i]:
    var spawns: Array[Vector2i] = []
    for cell in get_used_cells():
        var data := get_cell_tile_data(cell)
        if data and data.get_custom_data("is_spawn"):
            spawns.append(cell)
    return spawns

Pitfalls

常见陷阱

  • TileMap
    node is deprecated in 4.3.
    Use
    TileMapLayer
    nodes (one layer per node); group them under a parent
    Node2D
    . Old
    TileMap
    calls that took a
    layer
    argument (
    set_cell(layer, ...)
    ) do not apply to
    TileMapLayer
    .
  • local_to_map
    needs local coordinates.
    Mouse/global positions must be converted with
    to_local(...)
    first, or cells will be offset.
  • get_cell_tile_data
    returns
    null
    for empty cells or non-atlas sources — always null-check before
    get_custom_data
    .
  • Custom data is typed. A layer declared as
    int
    returns
    int
    ; reading it as the wrong type or referencing a non-existent layer name errors. Define the layer in the TileSet first.
  • Terrains need every combination defined.
    set_cells_terrain_connect
    produces odd results if the TileSet's terrain bitmask peering is incomplete.
  • Runtime edits are batched to end-of-frame. If you must read updated internals immediately after
    set_cell
    , call
    update_internals()
    (expensive — avoid in loops).
  • Collision not working? Check the layer's
    collision_enabled
    , that the tile has a physics layer with a polygon, and that the TileSet's physics layer mask matches your bodies.
  • TileMap
    节点在4.3版本中已弃用。
    请使用
    TileMapLayer
    节点(每个节点对应一个图层);将它们归到父节点
    Node2D
    下。旧
    TileMap
    中接受
    layer
    参数的调用(如
    set_cell(layer, ...)
    )不适用于
    TileMapLayer
  • local_to_map
    需要本地坐标。
    鼠标/全局位置必须先通过
    to_local(...)
    转换,否则单元格会出现偏移。
  • get_cell_tile_data
    可能返回
    null
    :空单元格或非图集资源会返回null,在调用
    get_custom_data
    前务必进行空值检查。
  • 自定义数据是类型化的。 声明为
    int
    的图层会返回整数类型;若读取时使用错误类型或引用不存在的图层名称会报错。请先在TileSet中定义该图层。
  • 地形需要定义所有组合。 如果TileSet的地形位掩码配对不完整,
    set_cells_terrain_connect
    会产生异常结果。
  • 运行时编辑会批量处理至帧末。 如果必须在调用
    set_cell
    后立即读取更新后的内部数据,请调用
    update_internals()
    (性能开销大,避免在循环中使用)。
  • 碰撞不生效? 检查图层的
    collision_enabled
    属性、瓦片是否带有包含多边形的物理图层,以及TileSet的物理图层掩码是否与你的物理体匹配。

References

参考资料

  • For TileSet setup (atlas sources, physics/navigation/custom-data layers, terrain bitmasks), scene tiles, Y-sorting, and runtime tile-data overrides (
    _use_tile_data_runtime_update
    ), read
    references/tileset-and-terrains.md
    .
  • 关于TileSet配置(图集资源、物理/导航/自定义数据图层、地形位掩码)、场景瓦片、Y轴排序以及运行时瓦片数据覆盖(
    _use_tile_data_runtime_update
    ),请阅读
    references/tileset-and-terrains.md

Related skills

相关技能

  • godot-2d-movement
    — characters that walk on these tiles.
  • godot-physics
    — collision layers/masks the tile collisions participate in.
  • procedural-gen
    — generating tilemaps from noise/RNG.
  • level-design
    /
    roguelike
    — design practice and grid-based genres.
  • godot-2d-movement
    — 在这些瓦片上行走的角色。
  • godot-physics
    — 瓦片碰撞所属的碰撞图层/掩码。
  • procedural-gen
    — 通过噪声/随机数生成瓦片地图。
  • level-design
    /
    roguelike
    — 关卡设计实践与基于网格的游戏类型。