Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check collision between certain divs

How can I check for collision between certain divs?

At the moment I'm using getBoundingClientRect(), but it checks for every div:

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

How would I go about checking specific ones? Using this for loop, I can get the IDs of the divs I want to check:

for (var x = 1; x <= noOfBoxArt; x++) {
    console.log('#boxArt' + x);
}
like image 811
Joey Morani Avatar asked Mar 19 '12 10:03

Joey Morani


People also ask

How to detect collision?

If both the horizontal and vertical edges overlap we have a collision. We check if the right side of the first object is greater than the left side of the second object and if the second object's right side is greater than the first object's left side; similarly for the vertical axis.

How do games check for collisions?

A hitbox is an invisible shape commonly used in video games for real-time collision detection; it is a type of bounding box. It is often a rectangle (in 2D games) or cuboid (in 3D) that is attached to and follows a point on a visible object (such as a model or a sprite).

What is collision JavaScript?

In JavaScript, a collision occurs when two or more HTML elements collide. By default, when using a move event listener on an HTML element, it will not hit any other element on the screen. It will pass through the other elements in the DOM.


1 Answers

Okay, I ended up using a modified version of this duplicate. The function which does the work is:

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

And it is called by using overlaps( div1, div2 ); (returns true or false).

like image 101
Joey Morani Avatar answered Sep 18 '22 05:09

Joey Morani