Tile Maps

A tile map builds a level out of a grid of same-sized cells: ground, walls, water, platforms. The engine doesn't have a map format of its own. It gives you a few helpers that take plain lists of cells, so your map can come from anywhere: strings written in code, arrays of tile ids, a generated layout, or a map made in Tiled (see Tiled maps).

The helpers, all in the BGE.TileMap namespace unless noted:

JobHelper
Draw thousands of tiles cheaplybakeTileMapImages()
Turn solid cells into a few colliders or solidsmergeTileColliderRuns()
Side-scroller collision (incl. one-way platforms)BGE.resolveAabbTileCollision()
Top-down movement against wallsBGE.SolidWorld
Pick border/corner tiles from neighboursgetEdgePiece3x3(), getNeighbourMask4(), getNeighbourMask8(), getBlobTileIndex()
Load a map made in Tiledloader.loadTiledMap() or BGE.Tiled.parseMapFile(), and friends
A 3D level written as rows of characters on the groundBGE.CharGrid, BGE.GridSides (see Text-grid levels on the ground)

examples/platformer (side-scrolling) and examples/rpg (top-down) use all of these; this guide follows how they do it.

Grid cells and world positions

Whatever your map data looks like, at some point you'll walk it row by row and turn each cell into a world position. Two things to keep straight:

  • Map rows usually count down from the top, but world +y is up. So row 0 is the highest row in the world.
  • Different helpers want different corners. Tile images and rectangle colliders take a top-left corner; BGE.SolidWorld takes a bottom-left corner.

A pair of small functions keeps that in one place:

CODE
const TILE_SIZE = 32

' Top edge of a cell row, in world space - for TileSpec.worldY and
' addRectangleCollider()'s offset_y.
function cellTopY(numRows as integer, row as integer) as float
  return (numRows - row) * TILE_SIZE
end function

' Bottom edge of a cell row - for BGE.SolidWorld.addSolid().
function cellBottomY(numRows as integer, row as integer) as float
  return (numRows - row - 1) * TILE_SIZE
end function

The rest of this guide uses these two names.

One way to write map data

Both example games write their maps as one string per row, one character per cell, with a legend in a comment:

CODE
' #  solid    -  one-way platform    .  empty
function getLevelRows() as string[]
  return [
    "........................",
    "..........---...........",
    "........................",
    "########....############"
  ]
end function

That's easy to read and edit in code, but it's only a choice: the helpers below never see the strings. An array of integer tile ids works just as well, and so does anything you can loop over.

Drawing the ground

Adding one Image per tile would give the renderer one object to sort and draw per tile, every frame. Instead, describe every tile as a BGE.TileMap.TileSpec and bake them into a few large bitmaps once, when the level is built:

CODE
override sub onCreate(args as roAssociativeArray)
  rows = args.rows
  numRows = rows.count()
  sheet = m.game.getBitmap("tiles")
  ' One region per tile kind, reused for every tile of that kind
  groundRegion = CreateObject("roRegion", sheet, 0, 0, TILE_SIZE, TILE_SIZE)

  tiles = [] as BGE.TileMap.TileSpec[]
  for r = 0 to numRows - 1
    for c = 0 to rows[r].len() - 1
      if rows[r].mid(c, 1) = "#"
        tiles.push({
          worldX: c * TILE_SIZE,
          worldY: cellTopY(numRows, r),
          region: groundRegion,
          width: TILE_SIZE,
          height: TILE_SIZE
        })
      end if
    end for
  end for

  chunks = BGE.TileMap.bakeTileMapImages(tiles, 512)
  for i = 0 to chunks.count() - 1
    chunk = chunks[i]
    region = CreateObject("roRegion", chunk.bitmap, 0, 0, chunk.bitmap.GetWidth(), chunk.bitmap.GetHeight())
    m.addImage("ground_" + i.toStr(), region, {
      offset: BGE.Math.VectorOps.create(chunk.worldX, chunk.worldY),
      drawMode: BGE.SceneObjectDrawMode.matchCamera
    })
  end for
end sub

Each chunk becomes one draw call. A tile can be any size and can be nudged off the grid (the platformer raises its grass tiles a few pixels so the player's feet line up with the art); a chunk's bitmap grows to fit.

512 is a good chunkSize. Larger chunks draw fine, but each chunk's bitmap covers its whole bounding box, so tiles far apart in one chunk spend texture memory on the empty space between them - and HD Roku devices have only 64MB of it.

Baking happens once, in onCreate(), so its cost is paid while the level loads rather than every frame.

Side-scrolling games

A side-scroller's tiles are real colliders, and the player is pushed back out of a tile after the engine reports an overlap.

Colliders for tiles

mergeTileColliderRuns() joins neighbouring cells in the same row that have the same tag, so a 20-tile floor becomes one collider instead of 20. Tag cells with whatever your game needs to tell apart:

CODE
cells = [] as BGE.TileMap.ColliderCell[]
for r = 0 to numRows - 1
  for c = 0 to rows[r].len() - 1
    ch = rows[r].mid(c, 1)
    if ch = "#"
      cells.push({row: r, col: c, tag: "solid"})
    else if ch = "-"
      cells.push({row: r, col: c, tag: "oneWay"})
    end if
  end for
end for

colliderRuns = BGE.TileMap.mergeTileColliderRuns(cells)
for i = 0 to colliderRuns.count() - 1
  colliderRun = colliderRuns[i]
  width = (colliderRun.endCol - colliderRun.startCol + 1) * TILE_SIZE
  collider = m.addRectangleCollider("tileRun_" + i.toStr(), width, TILE_SIZE, colliderRun.startCol * TILE_SIZE, cellTopY(numRows, colliderRun.row))
  collider.tagsList.add(colliderRun.tag)
end for

Landing, bumping and one-way platforms

In the player, remember where it was before this frame's movement, then let BGE.resolveAabbTileCollision() work out which side it hit:

CODE
override sub onUpdate(dt as float)
  m.positionBeforeMove = BGE.Math.VectorOps.create(m.position.x, m.position.y)
  ' ... gravity, running, jumping: set m.velocity ...
end sub

override sub onCollision(myCollider as BGE.Collider, otherCollider as BGE.Collider, otherEntity as BGE.GameEntity)
  if otherEntity.name <> "Level"
    return
  end if
  tile = otherCollider as BGE.RectangleCollider
  isOneWay = tile.tagsList.hasTag("oneWay")
  result = BGE.resolveAabbTileCollision(m.positionBeforeMove, m.position, m.width, m.height, m.velocity, tile, isOneWay)
  m.position.x = result.position.x
  m.position.y = result.position.y
  m.velocity.x = result.velocity.x
  m.velocity.y = result.velocity.y
  if result.side = BGE.TileCollisionSide.top
    m.grounded = true
  end if
end sub

The player's position is the bottom-centre of its hitbox. A one-way tile only stops a player landing on it from above; from below or the side it passes straight through.

Don't rely on onCollision() to keep the player grounded. The compositor doesn't always report the same overlap again on the next frame, so a player standing still can look like it keeps leaving the ground. Assume it's still grounded until it jumps or walks off an edge, and use onCollision() to detect new landings. See examples/platformer's Player.bs.

Cap dt for fast falls. This approach fixes an overlap after it happens, so a very long frame can move the player clean through a thin tile before any collision is seen. The platformer limits each update to 1/30s.

Top-down games

In a top-down game, characters walk around walls rather than landing on them, and it's simpler to keep them out of walls in the first place. BGE.SolidWorld does that with plain rectangle maths: no colliders, no velocity.

Walls

Feed the same merged rows into a SolidWorld, and fence in the map's edge:

CODE
world = new BGE.SolidWorld()
for each colliderRun in BGE.TileMap.mergeTileColliderRuns(cells)
  width = (colliderRun.endCol - colliderRun.startCol + 1) * TILE_SIZE
  world.addSolid(colliderRun.startCol * TILE_SIZE, cellBottomY(numRows, colliderRun.row), width, TILE_SIZE)
end for
world.addBounds(0, 0, numCols * TILE_SIZE, numRows * TILE_SIZE)

Keep one SolidWorld per scene and hand it to everything that walks.

Moving

Each frame, move a box at the character's feet and take its new position from the result:

CODE
sub moveBy(dx as float, dy as float)
  feet = {x: m.position.x - FEET_W / 2, y: m.position.y, w: FEET_W, h: FEET_H}
  result = m.solidWorld.moveAndSlide(feet, dx, dy)
  m.position.x = result.x + FEET_W / 2
  m.position.y = result.y
end sub

moveAndSlide() stops flush against walls, slides along them, splits a long move into short steps so nothing tunnels through, and eases the box around a corner it only just clips. Pass {cornerNudge: 0} for moves that shouldn't steer, like being knocked back.

Using only the feet lets a character's head overlap a wall drawn above it, which is what you want with a top-down camera.

Tracking bodies

When several things move a character in one frame (its own walking, a knockback, BGE.separateCircles() pushing it off another character), track it instead and resolve everyone once they have all moved. Each tracked body's move since the last resolve is replayed through moveAndSlide():

CODE
' Once, after adding the player: a 24x24 feet box centred on its position, on x and y
m.solidWorld.track(player, 12, {plane: BGE.SeparationPlane.xy})

' Each frame, in the scene's onPostUpdate(), after everything has moved:
override sub onPostUpdate(dt as float)
  BGE.separateCircles(m.bodies, BGE.SeparationPlane.xy)
  m.solidWorld.resolveTracked()
end sub

Or set the scene's trackedSolidWorld = m.solidWorld and the game calls resolveTracked() for you, right after onPostUpdate(). It's off until you set it. Call it yourself when something has to see the resolved positions in the same frame, like a camera that follows the player.

plane defaults to xz, the ground in a 3D game. Pass {slide: {cornerNudge: 0}} to give a body its own moveAndSlide() options. Track a body again after teleporting it (a respawn), or the jump is replayed as a move. untrack() stops tracking one body and untrackAll() everyone; invalidated entities are dropped on the next resolve. Override resolveTrackedBody() in a subclass to resolve some bodies differently, e.g. let a bat fly over walls.

Move inline when an entity needs the result straight away, e.g. to give up on a target once a wall stops it. examples/thirdPerson tracks its fighters; examples/rpg moves inline, since its NPCs read the result straight away and its knockbacks and lunges use different slide options from walking.

Colliders are still useful for things that trigger rather than block: a door, a pickup, an enemy's attack. examples/rpg uses onCollisionEnter() on a feet collider for doors.

Drawing in front of and behind things

Under BGE.Camera2d, a higher position.z draws in front. Set every character's and prop's z from its feet, so whatever is lower on screen draws in front, and push the ground far behind everything:

CODE
m.position.z = -m.position.y      ' characters and props, every time they move
groundEntity.position.z = -9000   ' the baked ground

Which collision approach?

resolveAabbTileCollision()BGE.SolidWorld
Works withCompositor colliders, in onCollision()Plain rectangles, no colliders
When it actsAfter an overlap is reportedBefore the move happens
One-way platformsYesNo
Stops fast movers tunnellingNo (cap dt)Yes
Slides along walls / eases cornersNoYes
Typical gameSide-scrolling, gravityTop-down, free movement

Auto-tiling

A path of cobblestones through grass looks blocky if every cobble cell uses the same picture. Auto-tiling picks each cell's tile from its neighbours, so borders and corners come out right without anyone choosing them by hand.

All the auto-tile functions take your grid as an array of rows. Each row is either a string, one character per cell, or an array of cell values such as integer tile ids. Two cells are the same surface when their values are equal.

A 3x3 edge set

The simplest tile sheet has nine pieces: four corners, four edges and a centre. getEdgePiece3x3() returns which one to use:

CODE
piece = BGE.TileMap.getEdgePiece3x3(rows, r, c)
region = CreateObject("roRegion", sheet, setX + piece.col * TILE_SIZE, setY + piece.row * TILE_SIZE, TILE_SIZE, TILE_SIZE)

A 3x3 set has no inner corners or one-cell-wide pieces, so those cells get the centre piece. Draw paths at least two cells wide, or use a bigger set.

16- and 47-tile sets

For more complete sheets, get a neighbour mask, where each matching neighbour sets one bit:

NW 128N 1NE 2
W 64E 4
SW 32S 16SE 8
  • 16 tiles (sides only): getNeighbourMask4() returns 0-15 using N = 1, E = 2, S = 4, W = 8, which indexes the set directly.
  • 47 tiles ("blob" sets, with inner corners): getNeighbourMask8() returns 0-255 with the bits above, and getBlobTileIndex() turns that into 0-46.
CODE
mask = BGE.TileMap.getNeighbourMask8(grid, r, c)
tile = BGE.TileMap.getBlobTileIndex(mask)
' this sheet lays its 47 tiles out 8 per row
region = CreateObject("roRegion", sheet, (tile mod 8) * TILE_SIZE, (tile \ 8) * TILE_SIZE, TILE_SIZE, TILE_SIZE)

There are only 47 because a corner only matters when both sides next to it also match. reduceBlobMask() clears the corners that don't, and getBlobTileIndex() numbers the 47 results in ascending order.

Your sheet's order may differ. Blob sheets from different tools lay out their 47 tiles differently. If yours doesn't match ascending-mask order, build your own lookup from reduceBlobMask()'s value to a tile position.

The map's edge

A neighbour outside the map counts as matching, so a path runs cleanly off the edge. Pass {outOfBoundsMatches: false} to draw a border there instead. A missing cell (past the end of a short row) or an invalid cell value also counts as outside the map.

Text-grid levels on the ground

In a 3D game the same rows of characters can lay out a level on the ground (x/z) instead of the screen: a maze, a town, a room full of furniture. BGE.CharGrid holds the rows and does the jobs every such map needs. What the characters mean stays up to your game.

CODE
' #  wall   =  table   T  torch   E  the way out
grid = new BGE.CharGrid([
  "#########"
  "#T.....T#"
  "#..===..#"
  "#..===..#"
  "####E####"
], {cellSize: 64})

for each cell in grid.cellsOf("T")
  center = grid.cellCenter(cell.col, cell.row)
  side = grid.wallSides(cell.col, cell.row)[0]   ' "n", "e", "s" or "w"
  addTorch(center, BGE.GridSides.normal(side))   ' your own entity
end for
for each table in grid.findRectGroups("=")
  center = grid.groupCenter(table)               ' one 3 x 2 table
  addTable(center, table.cols * 64, table.rows * 64)
end for
solids = grid.toSolidWorld()                     ' every `#`, and a wall round the grid

Row 0 is -z and column 0 is -x. The grid is centred on the world origin unless you pass an origin (the -x/-z corner of cell 0, 0). isSolid() counts solidKinds ("#" by default, "" for none) and everything outside the grid as solid; override it for anything else. Character matches are case-sensitive, so p and P can mean different things.

Finding things in the grid:

WantCall
Cells of some characters, or all but somecellsOf(kinds), cellsExcept(kinds)
Blocks drawn as rectangles (=== over two rows is one table)findRectGroups(kinds)
Connected blocks of any shape, as their bounding rectanglesfindConnectedGroups(kinds)
The rectangle round every cell of some characters, wherever they areboundsOf(kinds)
Straight runs (fences), along rows then down columnsfindRuns(kinds, minLength)
The cell a world position is in, its charactercellAt(x, z), kindAt(col, row), isKindOf(col, row, kinds)
Which sides of a cell face a wall or open floorwallSides(col, row), openSides(col, row)

BGE.GridSides turns a side into a [col, row] offset(), a unit normal(), its opposite() or the heading() that faces out through it. To hang something on a cell's wall (a picture, a torch bracket model), turn it by wallRotation(side): the rotation.y that faces a drawable or model built facing +z back into the cell.

CODE
side = grid.wallSides(cell.col, cell.row)[0]
painting.rotation = BGE.Math.VectorOps.create(0, BGE.GridSides.wallRotation(side), 0)

A rotation.y isn't a heading: something built facing +z, turned by r, faces BGE.Math.rotationForward(r), (-sin r, 0, cos r), so a quarter turn faces -x where a heading of a quarter turn faces +x. BGE.Math.rotationFacing(direction) goes the other way.

A level that keeps more than the grid (its start cell, its exits) can extend BGE.CharGrid:

CODE
class DungeonLevel extends BGE.CharGrid
  exits as BGE.CharGridCell[]

  sub new(rows as string[])
    super(rows, {cellSize: 192})
    m.exits = m.cellsOf("E")
  end sub
end class

To draw the walls, give the same rows to a BGE.GridWallsMap and a BGE.DrawableGridWalls (see Drawables and scene objects), with origin: grid.origin so they line up. A BGE.GridWallsCameraBoom keeps a chase camera out of those walls without colliders (see Third-person cameras). examples/thirdPerson's town, graveyard, crypt and interiors are all built this way.

Tiled maps

Tiled is a free map editor. Paint a level in it, place spawn points on an object layer, and load the result with BGE.Tiled. examples/platformer level 1 is a Tiled map (src/maps/level1.tmj): open it in Tiled to see how it's set up.

Saving from Tiled

  • Save the map as JSON (.tmj or .json).
  • Under Map > Map Properties, set Tile Layer Format to CSV or Base64 (uncompressed). Roku can't unpack zlib, gzip or zstd.
  • Keep tilesets in the map, or save them as JSON tilesets (.tsj). The XML .tsx format isn't read.
  • Use an Orthogonal map with a fixed size: isometric, hexagonal and infinite maps aren't supported.

Put the map, its tilesets and their images anywhere under pkg:/. Paths are followed relative to the file that names them, the way Tiled writes them.

Loading

CODE
map = BGE.Tiled.parseMapFile("pkg:/maps/level1.tmj")
if map = invalid
  ' the reason was printed: "[BGE.Tiled] ..."
end if

parseMapFile() reads local files, all at once. To load a map behind a loading screen, or from a URL, use the scene's loader instead (see Loading Assets). It loads the map, its external .tsj tilesets and every tileset image over as many frames as it takes:

CODE
override sub onLoad(loader as BGE.AssetLoader, args as roAssociativeArray)
  loader.loadTiledMap("level1", "https://example.com/maps/level1.tmj")
end sub

override sub onCreate(args as roAssociativeArray)
  map = m.game.getTiledMap("level1")
  ' layerToTileSpecs() uses the images that came with it
  tiles = BGE.Tiled.layerToTileSpecs(map, BGE.Tiled.getLayer(map, "ground"))
end sub

Tilesets and images resolve relative to the file that names them, so a map at a URL fetches them from beside it, and downloads are cached like any other. The images are in map.bitmaps (path to bitmap). A map that won't load (or whose tileset or an image won't) fails the task and isn't registered, so getTiledMap() returns invalid. game.unloadTiledMap("level1") frees it and its images. examples/platformer loads level 1 this way, and examples/loading's Remote assets scene downloads one.

The map's layers are in map.layers, in Tiled's order. Layers inside a group are listed in the group's place, so BGE.Tiled.getLayer(map, "ground") finds a layer wherever it is. Custom properties are plain lookups: map.properties.music, layer.properties.parallax.

Ground and colliders

A tile layer goes straight into the same baking and merging as above:

CODE
ground = BGE.Tiled.getLayer(map, "ground")

chunks = BGE.TileMap.bakeTileMapImages(BGE.Tiled.layerToTileSpecs(map, ground), 512)
' ...addImage() each chunk, as in "Drawing the ground"...

colliderRuns = BGE.TileMap.mergeTileColliderRuns(BGE.Tiled.layerToColliderCells(map, ground, "collision"))
' ...addRectangleCollider() each run, as in "Colliders for tiles"...

layerToTileSpecs() loads each tileset image and places every tile the way Tiled draws it:

  • Spritesheet and image-collection tilesets both work, including margin and spacing.
  • A tile bigger than a cell sits on the cell's bottom-left corner, unless the tileset's Tile Render Size is Map Grid Size, which fits it to the cell: stretched, or scaled evenly and centered when Fill Mode is Preserve Aspect Fit.
  • The tileset's Drawing Offset and the layer's offset move tiles, so a nudge like the platformer's 5px grass lip lives in the tileset, not in code.
  • Horizontally and vertically flipped tiles are drawn flipped. Rotated tiles draw unrotated and unflipped (a warning is printed).
  • A hidden layer gives no tiles. Opacity isn't baked into the images: set alpha: layer.opacity * 255 on the images you add for the chunks.
  • Each tileset image is loaded once per call. If your game already loaded some of them, pass {bitmaps: {"pkg:/sprites/tile.png": bitmap}} and those are used instead; images it has to load get added to the same lookup.

layerToColliderCells() makes a cell for every tile with a custom collision property, tagged with its value ("solid", "oneWay"). Hidden layers count, so collisions can live on a layer you don't draw. Pass a different property name to read another one. Set the property on the tile in the tileset editor, once, and every cell painted with that tile gets it.

To look at single cells, BGE.Tiled.getTileAt(map, layer, col, row) returns what's there (or invalid): its tileset, its tile entry with type and properties, and flipH/flipV. getLayerCells() lists every non-empty cell the same way.

World positions

Tiled measures in pixels from the map's top-left corner, with y going down. BGE.Tiled.toWorldY(map, y) turns that into a world y with the map's bottom edge at 0; toWorldX(map, x) passes x through. Both take an offset, and layerToTileSpecs() takes the same offsets as {offsetX, offsetY}, so tiles and objects stay lined up. The platformer uses this to put the bottom of its 11th row at world y 0, leaving the rows below it buried off screen.

Spawn points and other objects

An object layer's objects hold whatever you placed. Give each a Class in Tiled (it's read as type) and loop over them:

CODE
offsetY = 0
for each spawn in BGE.Tiled.getLayer(map, "spawns").objects
  x = BGE.Tiled.toWorldX(map, spawn.x)
  y = BGE.Tiled.toWorldY(map, spawn.y, offsetY)
  if spawn.type = "coin"
    coin = m.game.addEntity(new Coin(m.game))
    coin.position.x = x
    coin.position.y = y
  end if
end for

Each object has id, name, type, shape ("point", "rectangle", "ellipse", "polygon", "polyline", "tile" or "text"), x, y, width, height, rotation, visible and properties. Polygons and polylines have points relative to x/y. A rectangle's x/y is its top-left corner; a tile object's is its bottom-left, and its gid goes through BGE.Tiled.resolveGid() like a cell's.

Points are the simplest spawns: place each one where that entity's position goes.

Not supported

Object templates (only an object's own fields are read), animated tiles, Wang and terrain sets, and drawing image layers (their image path is read). Since Tiled saves the final tile for every cell, a Tiled map doesn't need auto-tiling; runtime auto-tiling is still useful for maps made in code or by the game, and for re-tiling around a cell that changes during play.