Premium Features
With collision blocks in place, let's implement the actual collision detection so our player stops when hitting them.
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 }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.heightCheck the player's velocity direction to determine if they're falling onto a block or hitting it from below.
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
No comments yet, be the first to add one