【问题标题】:Check collision between certain divs检查某些 div 之间的碰撞
【发布时间】:2012-03-19 10:09:24
【问题描述】:

如何检查某些 div 之间的冲突?

目前我正在使用getBoundingClientRect(),但它会检查每个 div:

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

我将如何检查特定的?使用这个for 循环,我可以获得我想要检查的 div 的 ID:

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

【问题讨论】:

标签: javascript collision-detection


【解决方案1】:

好的,我最终使用了 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 );调用(返回真或假)。

【讨论】:

    【解决方案2】:

    您也可以使用广受支持的getBoundingClientRect() 来实现此目的。

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-07
        • 2018-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多