I am making an online game and I use HTML5 canvas and Javascript to build my game.
I have some shapes and one ball that moves and when collided the shapes, the shapes should disapear.
the shapes and the ball are image and my big problem is how to detect collision between ball and shape because my shapes are rectangle, triangle, polygon and ... e.g.: This Shape
this is my code to detect collision but it just works for rectangles:
function collide(r1, r2) {
var dx = (r1.x + r1.width / 2) - (r2.x + r2.width / 2);
var dy = (r1.y + r1.height / 2) - (r2.y + r2.height / 2);
var width = (r1.width + r2.width) / 2;
var height = (r1.height + r2.height) / 2;
var crossWidth = width * dy;
var crossHeight = height * dx;
var collision = 'none';
if (Math.abs(dx) <= width && Math.abs(dy) <= height) {
if (crossWidth > crossHeight) {
collision = (crossWidth > (-crossHeight)) ? 'bottom' : 'left';
} else {
collision = (crossWidth > -(crossHeight)) ? 'right' : 'top';
}
}
return (collision);
}