HTML5 Game - Canvas Animation Collision Detection

Introduction

If two objects are colliding, they are overlapping.

You can use the following code to detecting a collision between rectangular objects.


if (!(rectB.x+rectB.width < rectA.x) &&   
    !(rectA.x+rectA.width < rectB.x) &&  
    !(rectB.y+rectB.height < rectA.y) &&  
    !(rectA.y+rectA.height < rectB.y)) {  
      // The two objects are overlapping  
};  
 

To check if two circle objects are colliding:

  
let dX = circleB.x - circleA.x;  
let dY = circleB.y - circleA.y;  
let distance = Math.sqrt((dX*dX)+(dY*dY));  
 
if (distance < circleA.radius + circleB.radius) {  

}  

Related Topics