Overlapping - canvas game

Question

How can I check if two rectangles are overlapping on the canvas?

Answer

You can check it by checking if there is any space between these two rectangles, on every side:

if (obstacle.x < player.x + player.width &&
   obstacle.x + obstacle.width > player.x &&
   obstacle.y < player.y + player.height &&
   obstacle.y + obstacle.height > player.y) {
      alert("collision detected");
}

Click me to see in work

2 Likes