简体   繁体   中英

canvas image collision with side detection

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 ... eg: 这个图片 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);

}

Just get your collision code to work for triangles and then it will work for all shapes! Here is the formula, in Javascript code for doing just that, taken from(mostly) this question .

function sign(p1, p2, p3) {
  return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]);
}

function inTriangle(point, trip1, trip2, trip3) {
  var b1 = sign(point, trip1, trip2) < 0.0;
  var b2 = sign(point, trip2, trip3) < 0.0;
  var b3 = sign(point, trip3, trip1) < 0.0;

  return  ((b1 == b2) && (b2 == b3));
}

With this code you just have to run, inTriangle(p, v1, v2, v3) , where p is the point your testing for, in collision detection that would be each of the corners of a shape, with a ball or circle just test some points on the circumference, v1; v2; v3 are the three points of a triangle your testing for.

Keep in mind that it is more efficient to test for the collision of a rectangle so if you have a shape that can be divided up like a rectangle, you should do so, instead of dividing it into triangles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM