How to detect a collision with JS

I am making my first game in canvas + javascript, just a space shooter. The problem is that I am using two nested loops to check if the missile hits the enemy like this:

if((enemies[i][1]>rocket_posy&&enemies[i][1]<rocket_posy+40)&&enemies[i]0]>rocket_posx&&enemies[i][0]<rocket_posx+12))

      

and this causes a small but still annoying lag. I've looked into this here and on google, but no one seems to bother with this as we have different mechanisms to do this. Does anyone know how to solve this problem without nested loops?

Thanks for the answer!

+3


source to share


1 answer


You can use a multidimensional tile array or hash table where the key is the x and y position. On collision in data structure, you fire your event for your collision.



0


source







All Articles