Search code examples
javascripthtmlcollisiondetection

Collision between two div vanillaJS no detection


I created a game for the web in vanilla js. I would like the console to detect a collision between two <img> tags. I am using the DOM to retrieve the items. With the arrows, I can move one of the images.

Problem: When they touch each other the console does not detect anything. It's written: no collision. I need the collisions to go to a next page / scene.

console.log('collisions');
// collision entre la limite et le personnage


let rect1 = document.getElementsByClassName('perso')
let rect2 = document.getElementsByClassName('obstacle');
console.log(rect1[0]);
console.log(rect2[0]);

if (rect1[0].x < rect2[0].x + rect2[0].width &&
  rect1[0].x + rect1[0].width > rect2[0].x &&
  rect1[0].y < rect2[0].y + rect2[0].height &&
  rect1[0].height + rect1[0].y > rect2[0].y) {
  console.log("collision");
  // window.location.href = 'htmlpage1.html';//passe à la page/scene suivante
} else {
  console.log("no collision");
}
#move {
  height: 300px;
  width: 300px;
  position: relative;
  z-index: 1;
}


/* limite de la page permet de passer à la scene suivante */

#limite {
  width: 150px;
  height: 250px;
  position: fixed;
  z-index: 2;
  margin: 30px 1100px;
  opacity: 50%;
}
<main>

  <div class="cadre">
    <img id="premierplan" src="../img/foreground.png" alt="premierplan">
    <img id="move" class="perso" src="../img/ne_bouge_pas_.gif" alt="image personnage">
    <img id="limite" class="obstacle" src="../img/carrebleu.png" class="cube" alt="frontiere">
  </div>

</main>


Solution

  • You have a few issues..

    1. getElementsByClassName returns an HTMLCollection, not a single element. You need to either iterate over these if you have more than one. Or if there's just one of each class, just use querySelector.
    2. If you want to use the element's x, y, you need to get it's DOMRect using getBoundingClientRect.

    Try this instead:

    let rect1 = document.querySelector('.perso').getBoundingClientRect();
    let rect2 = document.querySelector('.obstacle').getBoundingClientRect();