Tile Collisions in TCJSgame

In many games, characters and objects must interact with the environment by colliding with walls, platforms, or hazards. TCJSgame v3 makes this easy with the TileMap.crashWith() method. This checks whether a given Component collides with any tile in the map, or with tiles of a specific ID.

You can use crashWith(obj) to detect collision against all tiles, or crashWith(obj, id) to limit detection to tiles of a specific type. Combined with the Component.crashWith() method, this creates a powerful system for detecting and responding to collisions in grid-based levels.

Example


// Player component
let player = new Component(32, 32, "blue", 50, 50, "rect");
display.add(player);

// Basic map
let map = [
  [1,1,1,1,1],
  [1,0,0,0,1],
  [1,0,2,0,1],
  [1,1,1,1,1]
];
let ground = new Component(0, 0, "green", 0, 0, "rect");
let wall = new Component(0, 0, "brown", 0, 0, "rect");
let tilemap = new TileMap(display, map, [ground, wall], 480, 320);

function update() {
  tilemap.show();

  player.move();

  // Check collision with any tile
  if (tilemap.crashWith(player)) {
    console.log("Player hit a tile!");
  }

  // Check collision only with wall tiles (ID 2)
  if (tilemap.crashWith(player, 2)) {
    console.log("Player hit a wall!");
  }
}
    

Accessing Specific Tiles

Sometimes you need to retrieve a tile directly. Use rTile(tx, ty) to get the tile object at grid position (tx, ty). You can then read its properties or interact with it directly.


// Get the tile at (2,2)
let targetTile = tilemap.rTile(2, 2);
if (targetTile) {
  console.log("Tile ID:", targetTile.tid);
}
    
Note: The crashWith() method uses bounding box collision detection, based on the Component.crashWith() logic. If your tiles are rotated or scaled, collisions may not behave as expected. For grid-aligned games like platformers, however, this system is efficient and reliable.