检查某些div之间的冲突?

Joe*_*ani 5 javascript collision-detection

有谁知道如何检查某些div之间的冲突?目前我正在使用getBoundingClientRect(),但它检查每个div:

if (this.getBoundingClientRect()) {
    animateContinue = 1;
}
Run Code Online (Sandbox Code Playgroud)

我该如何检查具体的?使用这个for循环我可以得到我想要检查的div的ID.

for (var x = 1; x <= noOfBoxArt; x++) {
    console.log('#boxArt'+x);
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*ani 8

好的.使用此副本的修改版本结束.完成工作的功能是:

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width() / 2;
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();
Run Code Online (Sandbox Code Playgroud)

并通过使用overlaps( div1, div2 );(返回true或false)来调用.


Ben*_*ing 7

您还可以使用广泛支持的getBoundingClientRect()来实现这一点。

这是我使用以下教程开发的函数:

2D碰撞检测

// a & b are HTMLElements
function overlaps(a, b) {
  const rect1 = a.getBoundingClientRect();
  const rect2 = b.getBoundingClientRect();
  const isInHoriztonalBounds =
    rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x;
  const isInVerticalBounds =
    rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y;
  const isOverlapping = isInHoriztonalBounds && isInVerticalBounds;
  return isOverlapping;
}
Run Code Online (Sandbox Code Playgroud)