I\'m building a game in Javascript using canvas which requires collision detection, in this case if the player sprite hits a box, the player must not be allowed through the
I use the following function for collision detection between two rectangles:
rect_collision = function(x1, y1, size1, x2, y2, size2) {
var bottom1, bottom2, left1, left2, right1, right2, top1, top2;
left1 = x1 - size1;
right1 = x1 + size1;
top1 = y1 - size1;
bottom1 = y1 + size1;
left2 = x2 - size2;
right2 = x2 + size2;
top2 = y2 - size2;
bottom2 = y2 + size2;
return !(left1 > right2 || left2 > right1 || top1 > bottom2 || top2 > bottom1);
};
This determines whether two squares, centered at (x1, y1) and (x2, y2), with side lengths 2*size1 and 2*size2, respectively, are overlapping. It should be easy enough to alter the definitions of left1, right1, etc. to deal with general rectangles rather than just squares and to use a different data format.
Specifically, left1 is the left side of the the first square, right1 the right side, etc. Note that, in my coordinate system, the y-axis is inverted (top1 < bottom1).