0

I have a character "div" being drawn and controlled by me, also an enemy "div" being generated on the right (moving left) at different locations along the Y axis. I am trying to detect when those two divs touch (based on there absolute position left) is this possbile? I have only come across examples using an array of divs or canvas.

function drawPlayer() {
  let player = document.createElement('div');
  player.id = 'char';
  player.classList.add('character');
  player.classList.add('pixelart');
  player.style.position = 'absolute';
  player.style.top = '50%';
  player.style.left = '50%';
  document.querySelector('.bg').appendChild(player);
  let playersprite = document.createElement('img');
  playersprite.src = './sprites/chars/spritesheet1.png';
  playersprite.style.height = '576px';
  playersprite.style.width = '384px';
  playersprite.id = 'mainchar';
  document.querySelector('#char').appendChild(playersprite);
}

function generateObstacles() {

  let randomTime = Math.random() * 4000;
  let obstaclePos = 100;
  const obstacle = document.createElement('div');
  obstacle.classList.add('character');
  obstacle.classList.add('pixelart');
  document.querySelector('.bg').appendChild(obstacle);
  let obsprite = document.createElement('img');
  obsprite.src = './sprites/chars/spritesheet1.png';
  obsprite.style.height = '576px';
  obsprite.style.width = '384px';
  obsprite.id = 'mainchar';
  obstacle.appendChild(obsprite);
  obstacle.style.left = obstaclePos + '%';
  obstacle.style.top = getRandomInt() + '%';
  let enemyhit = obstacle.style.left + '%';
  let hitbox = document.querySelector('.character');
  var charhit = hitbox.style.left + '%';

  let timerId = setInterval(function () {
  // where i think my issue is \/
    if (enemyhit == charhit) {
      clearInterval(timerId);
      console.log('gameover');
    }
    obstaclePos -= 1;
    obstacle.style.left = obstaclePos + '%';
    obsprite.classList.add('faceleft');
    obsprite.classList.add('animation');
  }, 100);
  setTimeout(generateObstacles, randomTime);
}
generateObstacles();
tkausl
  • 13,686
  • 2
  • 33
  • 50
Jordan Silver
  • 159
  • 1
  • 1
  • 8
  • 1
    Could [this](https://stackoverflow.com/questions/5419134/how-to-detect-if-two-divs-touch-with-jquery) help you? – diiN__________ Mar 12 '21 at 13:28
  • 2
    Does this answer your question? [Check collision between certain divs](https://stackoverflow.com/questions/9768291/check-collision-between-certain-divs) – Keimeno Mar 12 '21 at 13:29
  • I am currently having trouble applying these solutions to my code, but i can visualize the path . at this moment im having trouble getting the divs i have to compare positions to the window so they can be tested for overlapping. – Jordan Silver Mar 12 '21 at 15:06
  • i got it! hahah – Jordan Silver Mar 12 '21 at 15:34

0 Answers0