EaselJS - Best way to detect collision
我正在为我的easylJS小型应用程序寻找一种冲突检测的好方法。
我刚刚使用createjs.Shape创建了2个矩形
但是在创建矩形形状之后,API不会让我知道矩形的宽度和高度(我不知道为什么)。
EaselJS Shape具有一个称为" hitTest"的方法,但仅在您要测试形状与点的碰撞时才可以使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //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(); } |
EaselJS不会让您知道文本和形状的宽度和高度是正确的。
这是EaselJS的局限性,但您实际上可以自己设置以下属性:
1 | blueRect.setBounds(x,y,width,height); |
从文档:
setBounds允许您手动指定对象的范围,这些对象不能计算自己的范围(例如Shape&Text)以供将来参考,或者可以将该对象包含在Container范围内。手动设置的边界将始终覆盖计算的边界。
然后,您可以通过请求blueRect.getBounds()来请求宽度和高度。
要检查两个矩形之间的冲突,可以使用以下代码,该代码接受两个矩形并在它们相交时返回true(我在stackoverflow的某处找到了此代码)
1 2 3 4 | 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; } |
这是fragenwissen.com的一个不错的功能,
它首先控制objs可见性,然后控制objs位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function detect_object_collision(obj1, obj2) { // user noname from FragenWissen.com if (obj1.visible && obj2.visible) { obj1.setBounds(obj1.nominalBounds.x + obj1.x, obj1.nominalBounds.y + obj1.y, obj1.nominalBounds.width, obj1.nominalBounds.height); obj2.setBounds(obj2.nominalBounds.x + obj2.x, obj2.nominalBounds.y + obj2.y, obj2.nominalBounds.width, obj2.nominalBounds.height); obj1 = obj1.getBounds(); obj2 = obj2.getBounds(); return !( ((obj1.y + obj1.height) < (obj2.y)) || (obj1.y > (obj2.y + obj2.height)) || ((obj1.x + obj1.width) < obj2.x) || (obj1.x > (obj2.x + obj2.width)) ); } else { return false; } } |
感谢@Kokodoko的解决方案,这是另一个使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function checkCollision(mc1, mc2) { m1x = mc1.x; m1y = mc1.y; m1w = mc1.nominalBounds.width; m1h = mc1.nominalBounds.height; m2x = mc2.x; m2y = mc2.y; m2w = mc2.nominalBounds.width; m2h = mc2.nominalBounds.height; if ( m1x >= m2x + m2w || m1x + m1w <= m2x || m1y >= m2y + m2h || m1y + m1h <= m2y) { return false; } else { return true; } } |