Reputation: 157
So I have been making this little shooter game with javascript and I have ran to a problem I cant figure out.
I have a collision check which checks if any alive enemy collides with the player or a bullet using a for loop. The loop runs fine until I spawn an enemy.
In the beginning of the for loop you can see console.log
, it logs numbers only till the first alive enemy's index
. For example if enemies[4]
is alive and no other enemies with index
before that are alive, it keeps logging 0, 1, 2, 3
and 4
. If I then kill all the enemies the loop runs full 50 times again (which is the length of the array) until an enemy spawns.
checkCollision: function(){
function calculate(enemy, other){
var r = enemy.r + other.r;
var dx = enemy.posX - other.posX;
var dy = enemy.posY - other.posY;
var d = Math.sqrt((dx * dx) + (dy * dy));
if(r > d){
enemy.alive = false;
other.alive = false;
return true;
}
return false;
}
for (var i = 0, max = this.enemies.length; i < max; i++) {
console.log(i);
if(this.enemies[i].alive){
if(calculate(this.enemies[i], this.player)){
continue;
}
for (var i = 0, max = this.player.weapon.bullets.length; i < max; i++){
if(this.player.weapon.bullets[i].alive){
if(calculate(this.enemies[i], this.player.weapon.bullets[i])){
break;
}
}
}
}
}
}
Here is a little visualization:
[0] = !alive
[1] = alive
[2] = !alive
[3] = alive
[4] = alive
Now the for loop would run only 2 times, therefore not checking the collision for 3 and 4, which is what i want it to do.
Upvotes: 0
Views: 113
Reputation: 5072
Well, you have a loop, which loops over all enemies, but checks only one enemy at a time and only against the player
, not against each other.
So try something like:
for (var i = 0, max = this.enemies.length; i < max; i++) {
for (var j = 0, max = this.enemies.length; j < max; j++) {
if(calculate(this.enemies[i], this.enemies[j]){
doSomething();
}
}
}
// Don't forget the player.
In case you are interested, there is a quite good HTML5 Game Development course which teaches you how to use an open source physics engine, which takes care of those things.
While looking for a job, I made a small version of Mario, using that open source project, and the info from that course. You can see the game on my website under "projects".
Edit
So after your example I understood your question. You are reusing the i
and max
variables in the inner loop about bullets. So if the inner loop finishes, the outer loop will also terminate as they both check i < max
.
Upvotes: 1