1

OK so I've tried one thing from a different question and it worked, but not the way I wanted it to. it didn't work the way I wanted it to! You literally had to click when two objects were touching so it would alert you, if somebody can figure out a way to detect if two elements are touching without having to click that would be a life saver! So I hope you people who read this request please respond if you know how. this is the code below. so one object is moving and i want it to make it stop when the object hits the player (i am making a game) the movement is by px.... i want it to keep testing if one object hits the player, and if it does i want it to stop everything.

var boxes = document.querySelectorAll('.box');

boxes.forEach(function (el) {
  if (el.addEventListener) {
      el.addEventListener('click', clickHandler);
  } else {
      el.attachEvent('onclick', clickHandler);
  }
})

var detectOverlap = (function () {
    function getPositions(elem) {
        var pos = elem.getBoundingClientRect();
        return [[pos.left, pos.right], [pos.top, pos.bottom]];
    }

    function comparePositions(p1, p2) {
        var r1, r2;
        if (p1[0] < p2[0]) {
          r1 = p1;
          r2 = p2;
        } else {
          r1 = p2;
          r2 = p1;
        }
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function (a, b) {
        var pos1 = getPositions(a),
            pos2 = getPositions(b);
        return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
    };
})();
function clickHandler(e) {

    var elem     = e.target,
        elems    = document.querySelectorAll('.box'),
        elemList = Array.prototype.slice.call(elems),
        within   = elemList.indexOf(elem),
        touching = [];
    if (within !== -1) {
        elemList.splice(within, 1);
    }
    for (var i = 0; i < elemList.length; i++) {
        if (detectOverlap(elem, elemList[i])) {
            touching.push(elemList[i].id);
        }
    }
    if (touching.length) {
        console.log(elem.id + ' touches ' + touching.join(' and ') + '.');
        alert(elem.id + ' touches ' + touching.join(' and ') + '.');
    } else {
        console.log(elem.id + ' touches nothing.');
        alert(elem.id + ' touches nothing.');
    }

}

this is my video game right now (please do not copy)

<!DOCTYPE html>
/
<html>
  <form id="player" class="box">
  </form>
  <button type="button" class="up" onclick="moveup()">^</button>
  <button type="button" class="down" onclick="movedown()">v
  </button>
<style src="style.css">
    #player {
width: 300px;
height: 100px;
background-color: blue;
 display: inline-block;
position: relative;
bottom: -250px;
left: 200px;


}
 .up {
 position: relative; 
 bottom: -400px;
  




 }
 .down {
 position: relative; 
 bottom: -420px;
 



 }
 body {
 background-color: black;



 }
 #car {
 width: 300px;
height: 100px;
background-color: red;
 display: inline-block;
position: relative;
bottom: -250px;
left: 600px;


 }
  </style>
  <form id="car" class="box"></form>
  <script>
  imgObj = document.getElementById('player');
imgObj.style.position= 'relative'; 
imgObj.style.bottom = '-250px'; 


function moveup() {
  imgObj.style.position= 'relative'; 
imgObj.style.bottom = '-250px'; 
  imgObj.style.bottom = parseInt(imgObj.style.bottom) + 70 + 'px';




}
function movedown() {
  imgObj.style.position= 'relative'; 
imgObj.style.bottom = '-250px'; 

 imgObj.style.bottom = parseInt(imgObj.style.bottom) + -120 + 'px';



}
myMove();
function myMove() {
  var elem = document.getElementById("car");   
  var pos = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 1000) {
      clearInterval(id);
      myMove();
    } else {
      pos++; 
      elem.style.left = pos + "px"; 
      elem.style.left = pos + "px"; 
  }
  }
  }
/* please do not copy; this is it so far i want the red box when it hits the player(blue box) to stop everything that is happening */
/* made by Jsscripter; car game */
  
 </script>
   </html>
Jsscripter
  • 61
  • 6
  • I think what you are looking is an algorithm of collision detection, probably this answer can help you: https://stackoverflow.com/a/41557359/1360383 – glrodasz Mar 07 '19 at 04:54
  • This might help you. Although there wasn't any straight answers. https://stackoverflow.com/questions/20254759/how-to-know-when-two-objects-touch-each-other – Aniket G Mar 07 '19 at 04:56
  • Looks like you just call `detectOverlap(element1, element2)` where `element1` and `element2` are set to the elements you want to check against. – Ouroborus Mar 07 '19 at 04:57
  • Possible duplicate of [Vanilla JS Div Collision Detection](https://stackoverflow.com/questions/41538882/vanilla-js-div-collision-detection) – diogenesgg Mar 07 '19 at 16:59

1 Answers1

0

Intersection observer. API was largely developed because of news feeds and infinite scrolling. Goal was to solve when something comes into view, load content. Also is a great fit for a game.

The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. This way, sites no longer need to do anything on the main thread to watch for this kind of element intersection, and the browser is free to optimize the management of intersections as it sees fit.

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

All major browsers except safari support the API. For backwards compatibility and Safari support can use the polyfill from W3C found here. Check out this example from MDN:

var callback = function(entries, observer) { 
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');

observer.observe(target);

See this in action here: https://codepen.io/anon/pen/OqpeMV

Joshua Robinson
  • 3,430
  • 1
  • 27
  • 35