首页 > 解决方案 > 如何使用 div 捕捉下降的 div?

问题描述

到目前为止,我已经在页面顶部生成了一些随机 div,并希望让它们从页面上掉下来。主要目的是当它们掉下来时,我希望右侧的蓝色 div “捕捉”下降的 div(当我们调整窗口大小时它会移动到“捕捉”)。所以每当蓝色 div 接触/碰撞?任何一个落下的div,落下的div在他们接触的准确位置粘在蓝色div上并停止下落——被抓到的div现在随着蓝色div一起移动。这会随着它“捕获”更多而逐渐增加。

我真的没有太多关于javascript的知识,而且当我在玩的时候,我想知道这是否可以用javascript来实现?有没有办法检测 div 触摸?

我附上了一个codepen: https ://codepen.io/cocotx/pen/vYmeBpr

window.addEventListener('load', init);

function init() {
  let shapes = [];
  let add = 0.1;

  var w = document.getElementById('falling-point').offsetWidth;
  var h = window.innerHeight;

  function randomInRange(from, to) {
      let x = Math.random() * (to - from);
      return x + from;
  };

  function createShape() {
    var div = document.createElement('div');
    div.setAttribute('class', 'shapes');
    div.style.left = randomInRange(0, w)+'px';
    div.style.top = 0+'px';
    const randomColor = Math.floor(Math.random()*16777215).toString(16);
    div.style.backgroundColor = "#" + randomColor;
    div.style.width = randomInRange(10, 90)+'px';
    div.style.height = randomInRange(20, 80)+'px';
    div.style.borderRadius = randomInRange(0, 50)+'px';
    div.style.borderRadius = randomInRange(0, 50)+'px';
    document.getElementById('main').appendChild(div);
    shapes.push(div);
  }

  function mainLoop() {
    let x = Math.random();
    if (x < 0.01) {
      createShape();
    }
    shapes.forEach(e => e.style.top -= add);
    requestAnimationFrame(mainLoop);
  }
  mainLoop();

};

任何帮助表示赞赏,在此先感谢!

标签: javascripthtmlcss

解决方案


有一个公式可以检测矩形之间的碰撞:

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.y + rect1.height > rect2.y) {
    // collision detected!
}

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


推荐阅读