Search code examples
collision-detectioneaseljs

EaselJS - Best way to detect collision


I'm trying to find a good way for collision detection for my easelJS small app.

I've just created 2 rectangle using createjs.Shape

But after creating a rectangle shape, the API doesn't let me know the width and height of the rectangle (I don't know why).

EaselJS Shape has a method called "hitTest" but it can only be used when you want to test collision of the shape and a point.

//Here's the code http://jsfiddle.net/ZbZjL/16/.

//Create a stage by getting a reference to the canvas
stage = new createjs.Stage("demoCanvas");
//Create a Shape DisplayObject.
redRect = new createjs.Shape();
redRect.graphics.beginFill("red").drawRect(0, 0, 60, 40);
redRect.regX = 30;
redRect.regY = 20;
redRect.x = 200;
redRect.y = 100;

blueRect = new createjs.Shape();
blueRect.graphics.beginFill("blue").drawRect(0, 0, 60, 40);
blueRect.regX = 30;
blueRect.regY = 20;
blueRect.x = 0;
blueRect.y = 100;
//Add Shape instance to stage display list.
stage.addChild(redRect);
stage.addChild(blueRect);
//Update stage will render next frame
stage.update();

document.addEventListener("mousemove", onMouseMove);
function onMouseMove(event) {
    blueRect.x = event.offsetX;
    stage.update();
}

Solution

  • It is correct that EaselJS does not let you know the width and height of text and shapes. This is a limitation of EaselJS but you can actually set these properties yourself:

    blueRect.setBounds(x,y,width,height);
    

    From documentation: setBounds allows you to manually specify the bounds of an object that either cannot calculate their own bounds (ex. Shape & Text) for future reference, or so the object can be included in Container bounds. Manually set bounds will always override calculated bounds.

    Then you can request the width and height by asking for blueRect.getBounds();

    To check collisions between two rectangles you can use this code, which takes two rectangles and returns true if they intersect (I found this code somewhere here on stackoverflow)

    this.checkIntersection = function(rect1,rect2) {
        if ( rect1.x >= rect2.x + rect2.width || rect1.x + rect1.width <= rect2.x || rect1.y >= rect2.y + rect2.height || rect1.y + rect1.height <= rect2.y ) return false;
        return true;
    }