I just (almost) finished a Space-Invaders game in Javascript. I have a few bugs to clear out of the way but meanwhile I wanted to ask how I can improve the method I use to test if one of my 'Bullets' has killed an 'Invader'.
I have a feeling I used too many loops and there must be a more elegant way.
The whole program may be found here.
The exact function is:
function testForInvaders(bullet){
var score = document.getElementById('score');
var bulletX = bullet.getLocation()[0],
bulletY = bullet.getLocation()[1];
for(var i = 0; i < Invaders.length; i++){
var invaderX = Invaders[i].getLocation()[0],
invaderY = Invaders[i].getLocation()[1];
if(Invaders[i].isVisible()){
// if bullet is in the invaders radius...
if(bulletX >= (invaderX - 15) && bulletX <= (invaderX + 15) &&
bulletY >= (invaderY - 15) && bulletY <= (invaderY + 15)){
Invaders[i].removeVisibility();
game.incrementScore();
game.updateScore(score);
return false;
}
}
}
return true;
}
This function is called from within my 'loop' function which is the interval the draws all elements to the canvas. The logic is as follows:
move all invaders (loop through them)
move all bullets (loop through them)
for each bullet I call the above function and test against all Invaders.
then I loop through everything once more to draw it to the canvas.
How can I improve this? General feedback would be welcome as well :)