Premium Features

Download Video

Collision detection

With collision blocks in place, we need to detect when our player hits them. In this lesson, we'll implement AABB collision detection and handle horizontal and vertical collisions separately for precise movement.

The Collision Detection Problem

When the player moves, they might overlap a collision block. We need to detect this overlap and push the player back to a valid position.

We check horizontal collisions first, then apply gravity and check vertical collisions. This order prevents corner-case bugs where the player gets stuck.

AABB Collision Formula

Two rectangles overlap when all four conditions are true:

function collision({ object1, object2 }) {   return (     object1.position.y + object1.height >= object2.position.y &&     object1.position.y <= object2.position.y + object2.height &&     object1.position.x <= object2.position.x + object2.width &&     object1.position.x + object1.width >= object2.position.x   ) }

Horizontal Collision Response

After moving horizontally, loop through collision blocks and check for overlap:

for (let i = 0; i < collisionBlocks.length; i++) {   const block = collisionBlocks[i]   if (collision({ object1: this, object2: block })) {     // Moving right - push player to left edge of block     if (this.velocity.x > 0) {       this.position.x = block.position.x - this.width - 0.01     }     // Moving left - push player to right edge of block     if (this.velocity.x < 0) {       this.position.x = block.position.x + block.width + 0.01     }   } }

Vertical Collision Response

After applying gravity, check for vertical collisions:

// Moving down (falling) if (this.velocity.y > 0) {   this.position.y = block.position.y - this.height - 0.01   this.velocity.y = 0 } // Moving up (jumping into ceiling) if (this.velocity.y < 0) {   this.position.y = block.position.y + block.height + 0.01   this.velocity.y = 0 }

Why the 0.01 Offset?

Floating-point precision can cause the player to still overlap after repositioning. The tiny offset prevents continuous collision detection from firing repeatedly.

Why This Matters

Proper collision detection is what makes a platformer feel solid. Without it, players would fall through floors or walk through walls.

Comments

Want to participate?

Create a free Chris Courses account to begin

Login

No comments yet, be the first to add one

Providing the lift to launch your development career

© 2026 Chris Courses. All rights reserved.