您好我开始在createjs中玩,我想检查如何检测碰撞。 我接近但是当我将元素移动到右边缘时效果不佳。可能是错误的?另外我知道它有插件但是在位图上工作而不是形状所以我不能用它作为基本的例子。 代码
var demo;
var demoInit = function(){
demo = new createjs.Stage('demo');
createjs.Ticker.setFPS(60);
demo.mouseMoveOutside = false;
var circle = new createjs.Shape();
circle.graphics.beginFill('red');
circle.graphics.drawCircle(0,0,60);
circle.x = demo.canvas.width/2;
circle.y = demo.canvas.height/2;
circle.alpha = 1;
circle.graphics.endFill();
circle.setBounds(0,0,120,120);
var controlsquare = new createjs.Shape();
controlsquare.graphics.beginFill('#ccc');
controlsquare.graphics.drawRect(0,0,100,100);
controlsquare.x = 200;
demo.addChild(controlsquare);
var shape1 = new createjs.Shape();
shape1.graphics.beginFill('green');
shape1.graphics.drawRect(0,0,100,100);
shape1.x = 30;
shape1.graphics.endFill();
var g = new createjs.Graphics();
g.setStrokeStyle(1);
g.beginStroke("#000000");
g.beginFill("red");
g.drawRect(0,0,20,100);
g.y = 20;
var shape2 = new createjs.Shape(g);
var container = new createjs.Container();
container.addChild(shape1,shape2);
container.x = 200;
container.y = 200;
container.setBounds(0,0,100,100);
container.addEventListener('pressmove',function(e){
createjs.Tween.get(container).to({x:e.stageX,y:e.stageY});
});
controlsquare.addEventListener('pressmove',function(e){
createjs.Tween.get(controlsquare).to({x:e.stageX,y:e.stageY});
});
demo.addChild(container);
circle.addEventListener('pressmove',function(e){
createjs.Tween.get(circle).to({x:e.stageX,y:e.stageY});
});
circle.addEventListener('click',function(e){
createjs.Tween.get(circle).to({scaleX:2,scaleY:2},3000);
circle.setBounds(0,0,240,240);
});
demo.addChild(circle);
createjs.Ticker.addEventListener('tick',function(e){
var circleBounds = circle.getBounds();
var circlePos = {
x:circle.x,
y:circle.y,
width:circleBounds.width,
height:circleBounds.height,
r:circleBounds.height/2
};
var containerBounds = container.getBounds();
var containerPos = {
x:container.x,
y:container.y,
width:containerBounds.width,
height:containerBounds.height
};
if ( RectCircleColliding(circlePos,containerPos)){
console.log('col happend');
}
demo.update();
});
var RectCircleColliding = function(circle,rect){
var distX = Math.abs(circle.x - rect.x-rect.width/2);
var distY = Math.abs(circle.y - rect.y-rect.height/2);
console.log(distX);
if (distX > (rect.width/2 + circle.r)) { return false; }
if (distY > (rect.height/2 + circle.r)) { return false; }
if (distX <= (rect.width/2)) { return true; }
if (distY <= (rect.height/2)) { return true; }
var dx=distX-rect.width/2;
var dy=distY-rect.height/2;
return (dx*dx+dy*dy<=(circle.r*circle.r));
}
};
window.onload = function(){
demoInit();
};