检查某些div之间的冲突?

时间:2012-03-19 10:09:25

标签: javascript collision-detection

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

if (this.getBoundingClientRect()) {
    animateContinue = 1;
}

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

for (var x = 1; x <= noOfBoxArt; x++) {
    console.log('#boxArt'+x);
}

3 个答案:

答案 0 :(得分:7)

好。使用this duplicate的修改版本结束。完成工作的功能是:

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

并使用overlaps( div1, div2 );调用(返回true或false)。

答案 1 :(得分:0)

纯JS版本

var overlaps = (function () {
    function getPositions( elem ) {
        var width = parseFloat(getComputedStyle(elem, null).width.replace("px", ""));
        var height = parseFloat(getComputedStyle(elem, null).height.replace("px", ""));
        return [ [ elem.offsetLeft, elem.offsetLeft + width ], [ elem.offsetTop, elem.offsetTop + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1 = p1[0] < p2[0] ? p1 : p2;
        var 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] );
    };
})();

答案 2 :(得分:0)

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

这是我使用位于以下位置的教程开发的功能:

https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection

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