Premium Features
Collision blocks
Our player can move freely, but there's nothing to stand on. In this lesson, we'll import collision data from Tiled map editor and render collision blocks that define where the player can and cannot go.
Understanding Tiled Data
Tiled exports collision layers as flat arrays. Each number represents a cell in the grid—0 means empty, 292 (our collision tile ID) means a collision block should be placed there.
The specific number (292) comes from Tiled's tile indexing system. Your value may differ depending on your tileset.
Parsing into a 2D Array
The flat array needs to be converted into rows. Create a utility function:
Array.prototype.parse2D = function() { const rows = [] for (let i = 0; i < this.length; i += 16) { rows.push(this.slice(i, i + 16)) } return rows } const parsedCollisions = collisionsLevel1.parse2D()16 is the number of columns in our Tiled map (1024px width ÷ 64px tiles).
The CollisionBlock Class
Each collision block is a simple rectangle:
class CollisionBlock { constructor({ position }) { this.position = position this.width = 64 this.height = 64 } draw() { c.fillStyle = 'rgba(255, 0, 0, 0.5)' c.fillRect(this.position.x, this.position.y, this.width, this.height) } }Creating Blocks from Data
Loop through the 2D array and create a block wherever you find the collision symbol:
const collisionBlocks = [] parsedCollisions.forEach((row, y) => { row.forEach((symbol, x) => { if (symbol === 292) { collisionBlocks.push(new CollisionBlock({ position: { x: x * 64, y: y * 64 } })) } }) })The indices (x, y) multiplied by 64 give us the exact pixel position.
Rendering Collision Blocks
In your animation loop, draw each block:
collisionBlocks.forEach(block => { block.draw() })The red semi-transparent blocks let you visualize collision areas during development. Later, you can make them invisible.
Why This Matters
This data-driven approach lets you design levels visually in Tiled and import them into your game. Change the map, re-export, and your game updates automatically—no manual coordinate entry required.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one