EaselJS-检测碰撞的最佳方法 [英] EaselJS - Best way to detect collision

查看:137
本文介绍了EaselJS-检测碰撞的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的easylJS小型应用程序寻找一种碰撞检测的好方法。

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

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

I've just created 2 rectangle using createjs.Shape

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

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具有一个称为 hitTest的方法,但是仅当您要测试形状与的碰撞时才可以使用。

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();
}


推荐答案

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

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);

从文档中:
setBounds允许您手动指定对象的边界,但不能计算它们自己的边界(例如Shape& Text)以供将来参考,否则该对象可以包含在Container边界中。

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.

然后,您可以通过请求blueRect.getBounds()来请求宽度和高度;

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

要检查两个矩形之间的冲突,可以使用此代码,该代码将两个矩形相交(如果我在相交处发现此代码,则返回true)

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;
}

这篇关于EaselJS-检测碰撞的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆