我正在检测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
,应将冲突轴设置为“ x” ...这是一个JSFiddle示例。当白色矩形与黑色矩形碰撞时,我的
collisionAxis
函数中的变量DetectCollision
应该设置为“ x”,因为closestSide = dright
,但是以某种方式将其设置为“ y”。谁能告诉我为什么?
最佳答案
它应该是,
if (closestSide == dleft || closestSide == dright) {
collisionAxis = "x";
}
if (closestSide == dtop || closestSide == dtopdbot) {
collisionAxis = "y";
}