1
votes

I am having a problem with setting up collision detection. I've followed a few posts from this forum and the web, but can't seem to get it to work. I am trying to use the square bounding box approach, located in a function.

Square is the shape that moves around the canvas with user input, and impactSquare is the stationary shape that I am trying to test the impact with. I can't seem to figure out what part is causing it not to work.

//square bounding box
if (impactSquare.x < square.x + square.width &&
    impactSquare.x + impactSquare.width > square.x &&
    impactSquare.y < square.y + square.height &&
    impactSquare.height + impactSquare.y > square.y) {
    // collision detected!
    //square.graphics.beginFill("#F4F4F4");
    console.log("Collision Detected");
} else {
    // no collision
    //square.graphics.beginFill("#FF0000");
    console.log("No Collision"); 
}
//stage.update();

Thank you for an help you can provide!

1
Could you provide a jsfiddle.net (and/or) any error messages that come up in the console? From just that code I do not see the problem with the collision. How often is this code called? - Spencer Wieczorek
That's the thing, I don't get any errors =) If I add a Ticker call, it just keeps writing "No Impact" over and over, even when there should be a collision. I am calling the function detectCollision(); in my init(); function. - Outdoor Photographer
But there is nothing wrong with this collision function (assuming everything else is correct), look at this Fiddle here: jsfiddle.net/AniHouse/zxe2a5aL. - Spencer Wieczorek

1 Answers

1
votes

You're probably having issues because you're trying the hitTest, which is pixel-perfect.

Here, use this: https://github.com/olsn/Collision-Detection-for-EaselJS works like a charm.

If the the intersection is empty, that's because there was no collision.

if (intersection !== null) {
   //  hit
} 

Cheers,