Reputation: 51
I am making a javascript game, and I can't make the enemy die when hit with a bullet. Here is the part of the code that I just can't understand:
for(var i=0;i<enemies.length;i++){
ctx.fillRect(enemies[i].x,enemies[i].y,30,100);
if(player.x+player.width>enemies[i].x && player.x<enemies[i].x+30 && player.y+player.height>enemies[i].y && player.y<enemies[i].y+100){
document.location.reload();
}
}
for (var b=0;b<bullets.length;b++){
ctx.beginPath();
ctx.arc(bullets[b].x,bullets[b].y,2,0,Math.PI*2);
ctx.fill();
bullets[b].x += bullets[b].dx;
if(bullets[b].x>enemies[i].x && bullets[b].x<enemies[i].x+enemies[i].width && bullets[b].y>enemies[i].y && bullets[b].y<enemies[i].y+enemies[i].height){
enemies.splice(i,1);
}
}
So, I know that the problem is that it can't read the property "x" of enemies[i] because I didn't put it in the enemies for loop, but if i put it there then it can't read the property "x" of bullets[b]. I've been stuck on this for two days now and searched everything I could find, but didn't find anything useful at all. I would appreciate any help... Thanks in advance!
Upvotes: 0
Views: 296
Reputation: 382274
What you want is to check all the ennemies, for each bullet.
This is done using nested loops:
for (var b=0;b<bullets.length;b++){
ctx.beginPath();
ctx.arc(bullets[b].x,bullets[b].y,2,0,Math.PI*2);
ctx.fill();
bullets[b].x += bullets[b].dx;
for (var j=ennemies.length; j-- >0;) {
if(bullets[b].x>enemies[j].x && bullets[b].x<enemies[j].x+enemies[j].width && bullets[b].y>enemies[j].y && bullets[b].y<enemies[j].y+enemies[j].height){
enemies.splice(j,1);
}
}
}
Note: In this example I loop over enemies in reverse order in order to avoid missing an ennemy when splicing.
Upvotes: 1