Vanilla JS Div Collision Detection

前端 未结 2 1783
孤街浪徒
孤街浪徒 2021-01-25 03:29

My implementation of the following can be found on jsfiddle.net

I have four divs. My goal is to make them draggable around the page but NOT to allow them to overlap one

2条回答
  •  盖世英雄少女心
    2021-01-25 03:54

    You will have the object colliding with more than just 1. The script will give you all the collisions. But the logic to accept/move it or no i guess depends on what it is you are trying to achieve. Borrowed from intersects

    script:

    function mouseMove(e) {
      if (!mouseDown) {
        return;
      }
      let coords = e.target.getBoundingClientRect();
      let movX = e.movementX;
      let movY = e.movementY;
    
      collision(movX, movY, e.target.classList[1], coords) //check all collisions. Item can collide with more than one polygon.
    
      e.target.style.left = `${coords.left+movX}px`;
      e.target.style.top = `${coords.top+movY}px`;
      /* if (!) {
    
      }*/
    }
    
    function collision(newX, newY, movingPart, movingRect) {
      let takenPositions = []; //array of arrays of rects' L, R, Top, Bottom coords
      let newCoords = {
        id: movingPart,
        width: 100,
        height: 100,
        x: movingRect.left + newX,
        y: movingRect.top + newY
      };
    
      let collision = false;
      let collisions = []; //store collisions. 
      divs.forEach((d) => {
        if (d.classList[1] !== movingPart) { // a thing can't collide with itself
          let c = d.getBoundingClientRect();
          takenPositions.push({
            id: d.classList[1],
            width: 100,
            height: 100,
             x: c.left,//updated this part x,y are undefined :|
             y: c.top //and updated this
          });
        }
      });
    
      takenPositions.forEach((p) => {
        var tw = p.width;
        var th = p.height;
        var rw = newCoords.width;
        var rh = newCoords.height;
        if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
          collision = false;
        } else {
          var tx = p.x;
          var ty = p.y;
          var rx = newCoords.x;
          var ry = newCoords.y;
          rw += rx;
          rh += ry;
          tw += tx;
          th += ty;
          collision = ((rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry));
          collisions.push({
            parentId: newCoords.id,
            destId: p.id,
            collision: collision
          });
        }
      });
      let info = document.querySelector('div.info');
      info.innerHTML = "";
      collisions.forEach(function(element) {
        info.innerHTML += `${element.parentId} collision with ${element.destId} is ${element.collision}.  
    `; }); }

提交回复
热议问题