JavaScript Bounded Box Collision Test

So at work I have been writing an HTML5/JavaScript drag and drop game. Totally new stuff for me. I am using the CreateJS library, check it out!

So I needed to detect if two items had a collision. These items were boxes and after some searching I found this YouTube video that helped me with the math.

I wanted to share the function I came up with for this.

Setup Boxes. I made objects, but you can just use regular variables for the numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
var boxA = {
top: 0,
right: 25,
bottom: 25,
left: 0
};

var boxB = {
top: 10,
right: 35,
bottom: 35,
left: 10
};

The function itself. Modify to fit your needs. In my first version I passed in 8 numbers.

1
2
3
4
5
6
function isCollision(boxA, boxB) {
return ((boxA.right >= boxB.left) &&
(boxA.left <= boxB.right) &&
(boxA.bottom >= boxB.top) &&
(boxA.top <= boxB.bottom));
};

Usage:

1
2
3
4
5
if (isCollision(boxA, boxB)) {
console.log("Collision");
} else {
console.log("No Collision");
}

Enjoy!