Collision detection using javascript

Collision Detection Using Javascript

car illustration from vectorstock.com

 

Hi… ? The simple fun exercise for collision detection with javascript.  In most of the game apps like car game, if car hits(collision) on the wall or any another car then you lose the game and need to play again. Now we’re going to see how to find if two elements are hits or not. Let’s see how it’s working.

DEMO

Code Contains

  • HTML
  • Javascript

Javascript

Function has two params – two elements.

By using 4 conditions check whether overlap occurs or not.

  • element_1.left < element_2.left + element_2.width
  • element_1.left + element_1.width  > element_2.left
  • element_1.top < element_2.top + element_2.height
  • element_1.top + element_1.height > element_2.top

If all are true, then collsion/overlap/hit whatever 🙂 occured.

Below code will helps to find same collision/hits/overlaps…..

function isCollapsed(element_1, element_2){
    if (element_1.left < element_2.left + element_2.width  && element_1.left + element_1.width  > element_2.left && element_1.top < element_2.top + element_2.height && element_1.top + element_1.height > element_2.top)
    {
        /*......Collision Occured.....*/
    }
}

DEMO

Thank you for reading this tutorial, and if you have any question or related work to show, please do. ?

You may also like