I'm trying to do collision detection between bullets and enemies in my game. But it's very unpredictable and sometimes it works, sometimes it doesn't (bullet goes straight through without doing anything) and sometimes it kills the script returning "Uncaught TypeError: Cannot read property 'x' of undefined".
The collision detection is just a trivial for loop like this:
if (enemies.length > 0 && bullets.length > 0) {
for (a = 0; a < bullets.length; a++) {
for (b = 0; b < bullets.length; b++) {
if (bullets[a].x + 36 >= enemies[b].x && bullets[a].x <= enemies[b].x + 56 && bullets[a].y >= enemies[b].y && bullets[a].y + 6 <= enemies[b].y + 69) {
bullets[a].Delete();
enemies[b].Delete();
}
}
}
}
The .Delete()
function is just a reference to arr.splice(index, 1)
in the objects. Of course I didn't expect this to be perfect, but I'm surprised by the random behaviour of it. What could cause this and how can I improve the collision detection?