EaselJS - 检测碰撞的最佳方法

Thị*_*hạm 4 collision-detection easeljs

我正试图为我的easelJS小应用程序找到一个很好的碰撞检测方法.

我刚刚使用createjs.Shape创建了2个矩形

但是在创建一个矩形形状后,API不会让我知道矩形的宽度和高度(我不知道为什么).

EaselJS Shape有一个名为"hitTest"的方法,但它只能在你想测试形状和点的碰撞时使用.

//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();
}
Run Code Online (Sandbox Code Playgroud)

Kok*_*oko 7

EaselJS不会让您知道文本和形状的宽度和高度是正确的.这是EaselJS的限制,但您实际上可以自己设置这些属性:

blueRect.setBounds(x,y,width,height);
Run Code Online (Sandbox Code Playgroud)

从文档:setBounds允许您手动指定对象的边界,这些对象无法计算自己的边界(例如Shape和Text)以供将来参考,或者因此对象可以包含在Container边界中.手动设置边界将始终覆盖计算的边界.

然后你可以通过询问blueRect.getBounds()来请求宽度和高度;

要检查两个矩形之间的碰撞,你可以使用这个代码,它接受两个矩形,如果它们相交则返回true(我在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;
}
Run Code Online (Sandbox Code Playgroud)