TileMapLayer
Most 2D levels are grids: ground, walls, platforms, water, decoration. Godot draws them with a TileMapLayer node, which paints tiles from a TileSet resource onto a grid of cells. A level usually has several layers stacked as sibling nodes: Background, Ground (with collision), Decoration in front of the player.
Migrating: Before Godot 4.3 there was one
TileMapnode holding several layers.TileMapis now deprecated in favour of oneTileMapLayernode per layer. To convert an old scene, select theTileMap, open the TileMap panel at the bottom, and use its tools menu to extract the layers as individualTileMapLayernodes. Methods lose theirlayerargument:tile_map.set_cell(0, coords, ...)becomeslayer.set_cell(coords, ...). Godot 3'sset_cellvandworld_to_mapare gone too.
The pieces
| Piece | What it holds |
|---|---|
TileSet (a resource, often saved as .tres) |
the tile size, plus physics layers, navigation layers, custom data layers, occlusion layers and terrain sets shared by all its tiles |
TileSetAtlasSource |
one tile sheet texture cut into tiles; each tile is addressed by its atlas coordinates (column, row) |
TileData |
per-tile settings: collision polygons, custom data values, probability, z-index ... |
TileMapLayer (a node) |
which tile is in which cell: (source_id, atlas_coords, alternative_tile) per cell |
So a cell is identified by three numbers: which source, which tile in that source, and which alternative (flipped or recoloured variant, 0 = the base tile).
Building a tile set in the editor
- Add a
TileMapLayernode to your level scene and name itGround. - In the Inspector, click Tile Set > New TileSet, then click the new resource to open it. Set Tile Size (for example 16×16).
- Open the TileSet panel at the bottom and drag your tile sheet PNG into its left column. Godot offers to create tiles in the non-transparent regions automatically: accept.
- Back in the Inspector, under Physics Layers, click Add Element. In the TileSet panel choose Paint, pick Physics Layer 0, and click the solid tiles to give them a full-square collision polygon.
- Switch to the TileMap panel, select a tile and paint in the 2D viewport (left click paints, right click erases; the rectangle and bucket tools are in the toolbar).
In a pixel-art game, also set Project Settings > Rendering > Textures > Canvas Textures > Default Texture Filter to Nearest, or the tiles look blurry.
Painting from code
Level generators, ASCII level files and editors-inside-your-game all fill a layer with set_cell(coords, source_id, atlas_coords). The runnable examples build a tiny TileSet in code from a blank image, because there are no image files here; the TileMapLayer calls are exactly what you'd use with an editor-made tile set:
extends Node2D
# frames: 0
const TILE := 16
const LEVEL := [
"..........",
"......C...",
"..##..##..",
"##########",
]
var map: TileMapLayer
func _ready():
# A TileSet with one atlas: tile (0, 0) = ground, tile (1, 0) = coin.
# In a real project the texture is your tile sheet PNG; here it's a blank image.
var atlas := TileSetAtlasSource.new()
atlas.texture = ImageTexture.create_from_image(Image.create(TILE * 2, TILE, false, Image.FORMAT_RGBA8))
atlas.texture_region_size = Vector2i(TILE, TILE)
atlas.create_tile(Vector2i(0, 0))
atlas.create_tile(Vector2i(1, 0))
var tile_set := TileSet.new()
tile_set.tile_size = Vector2i(TILE, TILE)
var source_id := tile_set.add_source(atlas)
map = TileMapLayer.new()
map.tile_set = tile_set
add_child(map)
for y in LEVEL.size():
for x in LEVEL[y].length():
match LEVEL[y][x]:
"#": map.set_cell(Vector2i(x, y), source_id, Vector2i(0, 0))
"C": map.set_cell(Vector2i(x, y), source_id, Vector2i(1, 0))
print("source id: ", source_id, ", cells used: ", map.get_used_cells().size())
print("used rect: ", map.get_used_rect())
print("coin cells: ", map.get_used_cells_by_id(source_id, Vector2i(1, 0)))
print("pixel (100, 40) is in cell ", map.local_to_map(Vector2(100, 40)))
print("cell (6, 1) centre is at ", map.map_to_local(Vector2i(6, 1)))
print("cell (2, 2) atlas coords: ", map.get_cell_atlas_coords(Vector2i(2, 2)))
print("cell (0, 0) source: ", map.get_cell_source_id(Vector2i(0, 0)), " (empty)")
map.erase_cell(Vector2i(6, 1)) # coin collected
print("after erase: ", map.get_used_cells().size(), " cells")
print("neighbour right of (2, 2): ", map.get_neighbor_cell(Vector2i(2, 2), TileSet.CELL_NEIGHBOR_RIGHT_SIDE))source id: 0, cells used: 15
used rect: [P: (0, 1), S: (10, 3)]
coin cells: [(6, 1)]
pixel (100, 40) is in cell (6, 2)
cell (6, 1) centre is at (104.0, 24.0)
cell (2, 2) atlas coords: (0, 0)
cell (0, 0) source: -1 (empty)
after erase: 14 cells
neighbour right of (2, 2): (3, 2)
The two conversions you'll use constantly:
local_to_map(position)→ which cell a point is in. The position is in the layer's local space; for a point in global coordinates, convert first withmap.local_to_map(map.to_local(global_point)).map_to_local(cell)→ the centre of a cell, in local space ((6, 1)→(6 * 16 + 8, 1 * 16 + 8)).
Empty cells return source id -1 and atlas coords (-1, -1). get_used_rect() is handy for setting camera limits to the level's size (see Camera2D).
Collision and custom data
Collision comes from the tile set's physics layers: each tile can have polygons on each physics layer, and every painted tile becomes part of one static body. Each physics layer has its own collision layer and mask, like any body (layers and masks).
Custom data layers attach your own typed values to tiles: damage, is_ladder, footstep_sound, friction. Code then asks the cell's TileData instead of hard-coding atlas coordinates. Here a player falls onto tile ground and walks right over a spike tile that has no collision but a damage value:
extends Node2D
# frames: 60
const TILE := 16
const GROUND := Vector2i(0, 0)
const SPIKES := Vector2i(1, 0)
var map: TileMapLayer
var player: CharacterBody2D
var last_cell := Vector2i(-1, -1)
func _ready():
var atlas := TileSetAtlasSource.new()
atlas.texture = ImageTexture.create_from_image(Image.create(TILE * 2, TILE, false, Image.FORMAT_RGBA8))
atlas.texture_region_size = Vector2i(TILE, TILE)
var tile_set := TileSet.new()
tile_set.tile_size = Vector2i(TILE, TILE)
tile_set.add_physics_layer() # physics layer 0
tile_set.add_custom_data_layer() # custom data layer 0
tile_set.set_custom_data_layer_name(0, "damage")
tile_set.set_custom_data_layer_type(0, TYPE_INT)
var source_id := tile_set.add_source(atlas)
atlas.create_tile(GROUND)
atlas.create_tile(SPIKES)
# Ground gets a square collision polygon (points are relative to the tile centre).
var h := TILE / 2.0
var ground_data := atlas.get_tile_data(GROUND, 0)
ground_data.add_collision_polygon(0)
ground_data.set_collision_polygon_points(0, 0, PackedVector2Array([Vector2(-h, -h), Vector2(h, -h), Vector2(h, h), Vector2(-h, h)]))
# Spikes have no collision, only data.
atlas.get_tile_data(SPIKES, 0).set_custom_data("damage", 2)
map = TileMapLayer.new()
map.tile_set = tile_set
add_child(map)
for x in 8:
map.set_cell(Vector2i(x, 3), source_id, GROUND)
map.set_cell(Vector2i(5, 2), source_id, SPIKES)
player = CharacterBody2D.new()
var shape := RectangleShape2D.new()
shape.size = Vector2(12, 12)
var cs := CollisionShape2D.new()
cs.shape = shape
player.add_child(cs)
player.position = Vector2(8, 0)
add_child(player)
func _physics_process(delta):
if not player.is_on_floor():
player.velocity.y += 980 * delta
player.velocity.x = 90
player.move_and_slide()
var cell := map.local_to_map(player.position)
if cell == last_cell:
return
last_cell = cell
var data := map.get_cell_tile_data(cell) # null for an empty cell
var damage: int = data.get_custom_data("damage") if data else 0
print("frame ", Engine.get_physics_frames(), ": cell ", cell, ", on floor ", player.is_on_floor(), ", damage ", damage)frame 1: cell (0, 0), on floor false, damage 0
frame 6: cell (1, 0), on floor false, damage 0
frame 11: cell (1, 1), on floor false, damage 0
frame 15: cell (1, 2), on floor false, damage 0
frame 16: cell (2, 2), on floor false, damage 0
frame 27: cell (3, 2), on floor true, damage 0
frame 38: cell (4, 2), on floor true, damage 0
frame 48: cell (5, 2), on floor true, damage 2
frame 59: cell (6, 2), on floor true, damage 0
get_cell_tile_data() returns null for an empty cell, so check it before reading custom data. The player stands on the ground row (row 3), so its centre is in row 2, where the spike tile is.
Beyond the basics
- Terrains (auto-tiling): define a terrain set in the
TileSet, mark each tile's edges and corners in the TileSet panel's Paint > Terrains mode, then paint with the Terrains tab. From code,set_cells_terrain_connect(cells, terrain_set, terrain)picks matching tiles for you. - Scene tiles: a
TileSetScenesCollectionSourceplaces whole scenes (a torch with a light, a breakable crate) as tiles. - Y-sorting: enable
y_sort_enabledon the layer (and its parent) for top-down games where characters walk behind tall tiles. - Navigation: navigation layers on the tile set let
NavigationAgent2Dpath across walkable tiles. - Large levels: a
TileMapLayerbatches its cells internally (seerendering_quadrant_size), so thousands of tiles are cheap, while thousands of individualSprite2Dnodes are not. Keep the number of layers small.
Test yourself
In Godot 4.3 and later, how do you build a level with ground and background tiles?
- One
TileMapnode with two layers - Two
TileMapLayernodes sharing aTileSet - A
GridMapnode - Sprite2D nodes placed by hand
With 16×16 tiles, what does map_to_local(Vector2i(2, 1)) return?
- (32, 16)
- (40, 24)
- (2, 1)
- (48, 32)
Where should a 'damage' value for spike tiles live?
- In a dictionary keyed by atlas coordinates in the player script
- In a custom data layer on the TileSet, read with
get_cell_tile_data(cell).get_custom_data("damage") - In the tile's texture
- In project settings