簡體   English   中英

檢查某些 div 之間的沖突

[英]Check collision between certain divs

如何檢查某些 div 之間的碰撞?

目前我正在使用getBoundingClientRect() ,但它會檢查每個 div:

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

我將如何檢查特定的? 使用這個for循環,我可以獲得我想要檢查的 div 的 ID:

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

好的,我最終使用了這個副本的修改版本。 完成工作的功能是:

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 );調用的overlaps( div1, div2 ); (返回真或假)。

您還可以使用廣泛支持的getBoundingClientRect()來實現這一點。

這是我使用教程開發的功能:

二維碰撞檢測

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

純 JavaScript 版本

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM