TileMaps in TCJSgame

The TileMap system in TCJSgame allows you to build large, grid-based levels using reusable tiles. Instead of drawing each block manually, you provide a map array, a list of available tile components, and then call TileMap.show() to render everything automatically.

A Tile is just a Component with extra properties (tx, ty, and tid) representing its grid position and ID. The TileMap class calculates tile sizes based on the canvas dimensions and the number of rows and columns in your map.

Example


// Define tiles (ID 1 = ground, ID 2 = wall)
let ground = new Component(0, 0, "green", 0, 0, "rect");
let wall = new Component(0, 0, "brown", 0, 0, "rect");

// Map: 0 = empty, 1 = ground, 2 = wall
let map = [
  [1,1,1,1,1],
  [1,0,0,0,1],
  [1,0,2,0,1],
  [1,1,1,1,1]
];

// Create TileMap
let tilemap = new TileMap(display, map, [ground, wall], 480, 320);

// Show the tiles
function update(){
	tilemap.show();
}
    

You can also edit maps dynamically:


// Add a wall at (2,2)
tilemap.add(2, 2, 2);

// Remove a tile at (1,1)
tilemap.remove(1, 1);

// Get all tiles of ID 1
let groundTiles = tilemap.tiles(1);
    
Note: The TileMap.show() method draws the entire map each time it is called. If you want tiles to update along with the rest of your game, you should call tilemap.show() inside your update() loop. Also remember that your map array must match the intended number of rows and columns of your level, or tiles will not render correctly.