检测2个div是否重叠,如果是,我检查矩形1的右侧和矩形2的左侧,矩形1的顶部和矩形2的底部,等等之间的距离。
if (rect1.right > rect2.left &&
rect1.left < rect2.right &&
rect1.top < rect2.bottom &&
rect1.bottom > rect2.top) {
//collision detected.
var dtop = Math.abs(rect1.top - rect2.bottom);
var dbot = Math.abs(rect1.bottom - rect2.top);
var dright =Math.abs(rect1.right - rect2.left);
var dleft = Math.abs(rect1.left - rect2.right);
var closestSide = Math.min(dtop,dbot,dright,dleft);
if (closestSide == dleft || dright) {
collisionAxis = "x";
}
if (closestSide == dtop || dbot) {
collisionAxis = "y";
}
alert("collisionAxis: " + collisionAxis);
return collisionAxis;
}
出于某种原因,collisionAxis始终设置为“y”,even when closestSide == dleft || dright
,应将collisionAxis设置为“x”...
这是一个JSFiddle示例。我的collisionAxis
函数中的变量DetectCollision
应该在白色矩形与黑色矩形碰撞时设置为“x”,因为closestSide = dright
,但不知何故它被设置为“y”。
有谁能告诉我为什么?
答案 0 :(得分:1)
应该是,
if (closestSide == dleft || closestSide == dright) {
collisionAxis = "x";
}
if (closestSide == dtop || closestSide == dtopdbot) {
collisionAxis = "y";
}