Premium Features
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.
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.
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 ) }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 } } }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 }Floating-point precision can cause the player to still overlap after repositioning. The tiny offset prevents continuous collision detection from firing repeatedly.
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
No comments yet, be the first to add one