How to Check for overlap Between Two Page elements Colission Detection

Check out the Collision Interactive at

Commonly in Games when page elements are moving, there needs to be a way to check if overlap has occurred. There is a formula that can be used which checks the x,y position of each element, as well needs the width and height of the element.

X-Horizontal check formula : (a.x < (b.x + b.width)) && ((a.x + a.width) > b.x);

y-Vertical check formula : (a.y < (b.y+b.height)) && ((a.y + a.height) > b.y);

To get the element information, about the size and position there is a method that can be used.

Element.getBoundingClientRect() method

The value that is returned from this element is the smallest rectangle of the entire page element, including the padding and border. This method can be applied to an element to get the bottom, left, right, and top position from the page. In addition the x, y, positions, relative to the top-left of the viewport, and the height and width of the page element.

console.log(box3.getBoundingClientRect());

The getBoundingClientRect() is a quick way to get all the values needed for collision detection. Select the page element and then add the method.

Use the querySelector to select the page element to use with the method. document.querySelector(‘.blocker’).getBoundingClientRect()

Learn JavaScript DOM Create Dynamic and Interactive Web Pages

Kindle Free Ebook for the next 3 days please note that Kindle is location dependant go the Amazon page for your country.

https://lsvekis.github.io/JavaScript-DOM-Collision-Detection/index.html

Source Code : https://github.com/lsvekis/JavaScript-DOM-Collision-Detection

Leave a Comment