Search code examples
javascriptcreatejs

CreateJS Collision Detection


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!


Solution

  • 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,