I am developping a spaceinvader-like game. There comes the problem of how to handle collision detection.
At first I was doing like that :
forEach(fireBall : fireBalls) {
forEach(stormTrooper : stormTroopers) {
if (collides(fireBall, stormTrooper)) {
// Explode
But then when playing I had the feeling the game was slowing down at some point, and I tought it had something to do with the multiple elements and the double loop.
So I tried to break the loops whenever I had the chance, changing the forEach loops to for loops at the same time :
for (var i = 0; i < fireBalls.length; i++) {
if (stormTroopers.length > 0 && fireBalls[i].y > stormTroopers[0].y) {
break;
}
for (var j = 0; j < stormTroopers.length; j++) {
if (fireBalls[i].y > (stormTroopers[j].y + 31)) {
break;
}
If the fireball isn't on the same "y" as any stormtrooper, the fireballs following are not going to be either, so no need to check. Same for the stormtroopers loop. This works only if the list is ordered, meaning the first stormTrooper of the list has the highest "y" value.
The problem in my game is that all stormTroopers don't have the same speed, so I need to sort the list each time.
This leads to my question : in order to enhance the performance, I tried to break the loops, but for that I had to add a new operation : sort the list of the stormTrooper. Is it worth it?