Tilemaps for 2D games: tile size, chunks, autotiles and layers

Every 2D game I have helped with at a jam eventually grows a tilemap, even the ones that swore they would not. You start with a few hand-placed platforms, then you want a second level, then you want to change the ground colour everywhere at once, and suddenly a grid of small numbers is the most sensible thing in the project. This piece walks through the decisions in the order you will actually meet them: how big a tile is, how the map lives in memory, how the edges join up on their own, how collision stays sane, and when to stop writing tools and open an editor.
I will keep the code in plain Rust so it fits whatever engine or framework you use. Drawing is left to you; a tilemap is mostly a data problem with a renderer on the end.
Step 1: pick a tile size and live with it
Tile size is the first decision and the hardest one to undo, because it touches the art, the camera, the physics and the level layouts all at once. The common choices are 8, 16 and 32 pixels, and each one pushes the game in a direction.
| Tile size | What it feels like | Good for | Watch out for |
|---|---|---|---|
| 8 px | Chunky, very readable, tiny sprites | Arcade games, small screens, jams | Characters need several tiles to show detail |
| 16 px | The classic handheld and console look | Platformers, top-down adventures | Detail budget is real but tight |
| 32 px | Room for shading and texture | Strategy, farming games, larger worlds | More drawing per tile, slower to iterate |
My default for a jam is 16 pixels. It is small enough that one person can draw a full set in an afternoon and large enough that a grass tile can still have two shades and a flower.
Then do the camera maths before you draw anything. Suppose the internal resolution is 320 by 180, which scales cleanly to 1280 by 720 (4x) and 1920 by 1080 (6x). With 16 pixel tiles that screen holds 20 tiles across and 11.25 tiles down. That quarter tile at the bottom is fine for a scrolling game but annoying for single-screen rooms, where you may prefer 320 by 176 or let the bottom row sit under the HUD. If integer scaling and pixel snapping are new to you, the piece on the pixel art camera covers why the scale factor should stay a whole number.
Step 2: store the map as plain numbers
A tile on disk and in memory is just an index into a tileset. Zero usually means empty. Store the grid as a flat vector and do the row maths yourself; it is faster than a vector of vectors and easier to serialise.
pub const TILE: u32 = 16;
pub struct TileLayer {
pub width: u32,
pub height: u32,
pub tiles: Vec<u16>, // 0 means empty, otherwise tileset index + 1
}
impl TileLayer {
pub fn new(width: u32, height: u32) -> Self {
Self { width, height, tiles: vec![0; (width * height) as usize] }
}
pub fn get(&self, x: i32, y: i32) -> u16 {
if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 {
return 0; // outside the map counts as empty
}
self.tiles[(y as u32 * self.width + x as u32) as usize]
}
pub fn set(&mut self, x: u32, y: u32, id: u16) {
let i = (y * self.width + x) as usize;
self.tiles[i] = id;
}
}
Two small choices in there save trouble later. get takes signed coordinates and returns empty outside the map, so
neighbour checks at the edge never panic. And the ids are u16, which allows thousands of tiles and keeps a 256 by
256 layer at 128 KB.
Converting between world positions and tiles is one division, and the only trap is negative numbers. Use
div_euclid so that a position of minus 3 pixels lands in tile minus 1, not tile 0:
pub fn world_to_tile(px: f32, py: f32) -> (i32, i32) {
let t = TILE as i32;
((px.floor() as i32).div_euclid(t), (py.floor() as i32).div_euclid(t))
}
Step 3: chunk it when the map gets big
A single-screen puzzle game never needs chunks. A side-scroller with long levels or a top-down world that the player can dig into usually does. The idea is simple: split the map into fixed squares, often 16 by 16 or 32 by 32 tiles, and treat each square as a unit for drawing, saving and rebuilding.
Here is the worked example that convinced me. A 512 by 512 tile world is 262,144 tiles. If every tile is drawn every frame, that is a quarter of a million quads before any characters. With 32 by 32 chunks you have a 16 by 16 grid of 256 chunks. The 320 by 180 view covers 20 by 12 tiles, which touches at most two chunks across and two down, so four chunks on screen. That is 4,096 tiles to consider instead of 262,144, and you find them with two divisions.
Chunks also give you a natural place to cache work. When a tile changes, mark only its chunk dirty and rebuild that
chunk's vertex data. When saving, write only chunks that differ from the generated original. Keep chunks in a
HashMap<(i32, i32), Chunk> and the world can even be unbounded, filling in chunks as the player walks.
The cost is a little more indexing code and one classic bug: autotiling and collision checks that look at
neighbours must be able to see across a chunk border. Route every neighbour lookup through a world-level get
that finds the right chunk, and never read a chunk's array directly from outside it.
Step 4: let the edges join themselves with autotiling
Drawing a cliff by hand means choosing the right corner, edge and inner piece for every cell. Autotiling does it for you by looking at the neighbours. The simplest version checks the four orthogonal neighbours and builds a 4-bit mask:
pub fn edge_mask(layer: &TileLayer, x: i32, y: i32, solid: u16) -> u8 {
let same = |dx: i32, dy: i32| layer.get(x + dx, y + dy) == solid;
let mut m = 0;
if same(0, -1) { m |= 1; } // up
if same(1, 0) { m |= 2; } // right
if same(0, 1) { m |= 4; } // down
if same(-1, 0) { m |= 8; } // left
m
}
That gives 16 combinations, and you draw 16 tiles to match: an isolated block, end caps, straight runs, corners,
T-junctions and a fully surrounded centre. Lay them out in the tileset in mask order, so mask 5 (up and down) sits at
column 5, and the lookup is just base + mask.
The 4-bit version has one visible weakness: inner corners. Where two walls meet at an L, the inside corner needs a little notch that the orthogonal neighbours cannot detect. The fix is to also check the diagonals, but only when both neighbouring sides are present. A diagonal only matters if up and right are both solid, for example. With that rule the 256 raw combinations collapse to 47 distinct tiles, which is why you will see "47-tile blob sets" mentioned in tileset packs and editor docs.
My advice: start with 16. Draw them quickly, ship the jam, and only move to the 47-tile set if inner corners actually bother you in screenshots. Many lovely games live happily with 16 and a few hand-placed decoration tiles on top.
A practical trick for terrain blends
For grass meeting sand, draw transitions as an overlay layer instead of baking every pair into the base set. The base layer holds pure grass and pure sand; a second layer, autotiled against sand, places the grassy fringe on top. Three terrains then need three fringe sets rather than a combinatorial pile.
Step 5: keep collision on its own layer
It is tempting to say "tiles 1 to 40 are solid" and read collision straight from the visual layer. It works until an artist adds a pretty variant of a wall tile and forgets to add it to the list, and your hero falls through a castle.
Keep a separate collision layer with a handful of meanings instead:
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Solid {
Empty = 0,
Wall = 1,
OneWay = 2, // platforms you can jump up through
Hazard = 3,
Ladder = 4,
}
The visual layers can then be as messy and decorative as you like. The collision layer stays boring, which is exactly what you want from the thing that decides whether the player dies. You can generate it from the visual layer with a per-tile property, paint it by hand in the editor, or both, with manual paint overriding.
For movement, tile collision is pleasantly cheap: work out the tiles a moving box overlaps, test only those, and resolve one axis at a time. Move on x, push out of any walls, then move on y and push out again. Doing both axes at once is how characters snag on the seams between two floor tiles. Run this inside a fixed timestep loop and the results stay the same at any frame rate.
Step 6: layers for drawing order
A small game usually wants three to five visual layers:
- Background: sky, far walls, anything behind the player.
- Ground: the main terrain the player stands on.
- Decoration: grass tufts, cracks, signs, all non-colliding.
- Foreground: tree canopies, arches and pillars that the player walks behind.
- Collision: never drawn in the release build, drawn in a debug colour while testing.
Foreground is the layer people forget, and it adds a lot of depth for very little work. A row of leaves drawn after the player makes a forest feel like a place rather than a floor plan. For more on depth, the parallax backgrounds piece shows how to push the background layer further back.
Step 7: use an editor before you write one
Writing a level editor is fun, and it will eat your jam. Tiled and LDtk both export maps as JSON, both understand layers, and both support rule-based autotiling, so you can paint terrain and let the editor pick edge tiles. Tiled is a general tool that many engines read; LDtk leans towards structured levels with entities and typed fields. Either will save you days.
A sensible pipeline is: paint in the editor, export JSON, load it with serde into your own TileLayer structs, and
keep your runtime format simple. Your game should not care which editor made the file, only that the numbers arrive.
Questions people ask
Should tiles be square?
For most games, yes. Isometric and hexagonal maps are lovely but change the coordinate maths, the sorting and the art, so treat them as a separate project rather than a variation.
How do I stop thin lines appearing between tiles?
Those seams usually come from sampling slightly outside a tile in the atlas when the camera sits between pixels. Snap the camera to whole pixels and add one or two pixels of padding around each tile in the atlas, repeating the edge colour.
Can I animate tiles?
Yes. Store animated tiles as a short list of frames and advance a global timer, so every water tile shares the same frame. Rebuilding the chunk is not needed if the renderer offsets the atlas lookup per frame.
How big should a level be?
For a jam, smaller than you think. Three screens of carefully placed tiles beat thirty screens of filler. The jam scoping guide has a way to budget it.
For a first exercise, take a 20 by 12 grid, paint a single solid terrain with random noise, and run the 4-bit mask over it. Seeing the cliffs snap into shape on their own is the moment tilemaps start to feel like magic.
Filed in 2D Craft · Engines & Architecture

Written by Jun Takemura
Jun draws and animates pixel art and writes about the craft side of 2D games: sprites, tiles, palettes, animation and the small design choices that make a game feel finished. Lives in Osaka and never misses a jam weekend.
