Vanilla JS Div Collision Detection

前端 未结 2 1781
孤街浪徒
孤街浪徒 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:56

    This is a bit more complex than it looks.

    Essentially what you need to do is get both sets of coordinates, those for the current (moving) element, and the one with which it has collided. Once a collision is detected, find out which axis has the smallest difference, then snap those coordinates.

    var ac = a.getBoundingClientRect(); // coordinates for element 'a'
    var bc = b.getBoundingClientRect(); // and 'b'
    
    // assuming both boxes are same size...
    // if not, use your existing collision code.
    
    if(Math.abs(ac.top - bc.top) < ac.height && Math.abs(ac.left - bc.left) < ac.width) {
    // collision here...
    
        if(Math.abs(ac.top - bc.top) < Math.abs(ac.left - bc.left)) {
        // vartical offset is smaller, so snap 'y's
    
            if(ac.top < bc.top) { // a is above b, so snap a's bottom to b's top
                a.style.top = bc.top - ac.height - 1 + 'px';
            }
            else {
                a.style.top = bc.top + bc.height + 1 + 'px';
            }
    
        }
        else { // here, horizontal offset is smaller, so snap 'x's
    
            if(ac.left < bc.left) { // a is to the left of b, so snap a's right to b's left
                a.style.left = bc.left - ac.width - 1 + 'px';
            }
            else {
                a.style.left = bc.left + bc.width + 1 + 'px';
            }
    
        }
    
    }
    

    That should solve your problem...

提交回复
热议问题