check collision between certain divs?

℡╲_俬逩灬. 提交于 2019-12-30 06:17:25

问题


Anyone know how to check for collision between certain divs? At the moment I'm using getBoundingClientRect(), but it checks for every div:

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

How would I go about checking specific ones? Using this for loop I can get the IDs of the divs I want to check.

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

回答1:


Okay. Ended up using a modified version of this duplicate. The function which does the work is:

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

and is called by using overlaps( div1, div2 ); (returns true or false).




回答2:


Pure JS version

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



回答3:


You can also use the widely supported getBoundingClientRect() to achieve this.

Here's the function I developed using the tutorial found at:

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


来源:https://stackoverflow.com/questions/9768291/check-collision-between-certain-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!