Search code examples
javascriptset-intersection

Dictate that elements have intersected each other


Am working on a JavaScript simple game (game like one google chrome shows on no network presence).

I would like to dictate that the incoming span is in contact with the first span. (trouble intersected with actor)

enter image description here

Current approach

let actor = $(el).find(".actor");
let mainOffset = toOffset($(actor).offset());
let incomingTrouble = $(".trouble")[0];
if(typeof incomingTrouble==="undefined")return;
let offset = toOffset($(incomingTrouble).offset());
if(offset.left<1){
    $(incomingTrouble).removeClass("trouble");
}
if((offset.left>0 && offset.left===mainOffset.left) && offset.top<=mainOffset.top){
    console.log("Dead");
    $("button").trigger("click");
    //Game over
}

The code above has a problem, if actor drops and the trouble isn't yet hidden its dictating that the game is over yet in real sense these have not intersected.

hint:

toOffset(...) return two decimal place offset.left and offset.top

html

<div class="" tabindex="0" id="jump_game">
    <section>
        <!-- game actor -->
        <span class="actor"><i class="zmdi zmdi-bike"></i></span>

        <!-- game strangers -->
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        <span class="trouble stranger"><i class="zmdi zmdi-block"></i></span>
        
    </section>
    <button><i class="zmdi zmdi-play"></i></button>
</div>

Solution

  • Thanks to our colleagues who pointed me to JavaScript: Collision detection

    This solves my problem.

    function isCollide(a, b) {
        var aRect = a.getBoundingClientRect();
        var bRect = b.getBoundingClientRect();
    
        return !(
            ((aRect.top + aRect.height) < (bRect.top)) ||
            (aRect.top > (bRect.top + bRect.height)) ||
            ((aRect.left + aRect.width) < bRect.left) ||
            (aRect.left > (bRect.left + bRect.width))
        );
    }
    

    Thanks