Premium Features

Download Video

Collision detection

With collision blocks in place, let's implement the actual collision detection so our player stops when hitting them.

The Collision Algorithm

For each frame, we check if the player's next position would overlap with any collision block. The basic formula:

if (   player.position.x + player.width >= block.position.x &&   player.position.x <= block.position.x + block.width &&   player.position.y + player.height >= block.position.y &&   player.position.y <= block.position.y + block.height ) {   // Collision detected }

Handling Vertical Collisions

When the player lands on a block, set their Y velocity to zero and position them exactly on top:

player.velocity.y = 0 player.position.y = block.position.y - player.height

Check the player's velocity direction to determine if they're falling onto a block or hitting it from below.

Handling Horizontal Collisions

When the player walks into a block, stop horizontal movement and snap them to the block's edge. Check velocity to determine which side they hit.

With collision detection working, your player now interacts with the level geometry.

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.