Collision two divs in Javascript

  collision, javascript

Iam trying to get collision between two divs(1st is circle, 2nd is rect) which are controlled by arrows.
When the div1 touches div2, the div1 should be placed back to a start position.

The div1 is not getting to start position after the collision.
Iam getting an else alert("test1") when pressing the arrow to move div.

code:

let div1 = document.getElementById('div1').getBoundingClientRect();
let div1Top = div1.top;
let div1Left = div1.left;
let div1Right = div1.right
let div1Bottom = div1.bottom

let div2 = document.getElementById('div2').getBoundingClientRect();
let div2Top = div1.top;
let div2Left = div1.left;
let div2Right = div1.right
let div2Bottom = div1.bottom

if ((div2Top > div1Top && div2Top < div1Bottom)||(div2Bottom > div1Top && div2Bottom < div1Bottom)) {
  div1.style.top = 0 + "px";
} else{
  alert("test1");
}

if ((div2Right > div1Left && div2Right < div1Right)||(div2Left < div1Right && div2Left > div1Left)) {
  div1.style.top = 0 + "px";
} 
else{
  alert("test");
}


Source: Ask Javascript Questions

LEAVE A COMMENT