0

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>
James in code
  • 73
  • 1
  • 6
  • I have founded an answer on your first comment which directed me to https://stackoverflow.com/questions/2440377/javascript-collision-detection – James in code Apr 07 '21 at 22:30
  • Just BTW, this might be worth a look: [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). – yaakov Apr 07 '21 at 22:38

1 Answers1

0

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

James in code
  • 73
  • 1
  • 6