How to detect and subtract a variable under a for and if loop?

Viewed 44

I have a bunch of objects that when they fall out of screen, it wont stop subtracting.

for (var i = 0; i < maximum_number_objects_spawned; i++){
    if (objects[i].y > game_height){
        lives = lives - 1;
    }
}

For context, I am using a gravity engine to pull these objects down, so it isn't really applicable to use an if "objects[i] is equal to the world_height" statement. Here is something I tried that didn't work:

for (var i = 0; i < maximum_number_objects_spawned; i++){
    lives_not_subtracted = true;
if (objects[i].y > game_height && lives_not_subtracted === true){
        lives = lives - 1;
        lives_not_subtracted = false;
    }
}

This still did not work and rather continued to subtract lives infinitely. I am curious as to see why my second method did not work, although it looks as if it should've.

1 Answers

Your loop is wrong, lives_not_subtracted will always true, place it outside the loop or in object like below

var objects = [{
    y: 555,
    lives_not_subtracted: true
  },
  {
    y: 444,
    lives_not_subtracted: true
  }
]

for (var i = 0; i < maximum_number_objects_spawned; i++) {
  if (objects[i].y > game_height && objects[i].lives_not_subtracted == true) {
    lives = lives - 1;
    objects[i].lives_not_subtracted = false;
  }
}

or check existence of lives_not_subtracted if not exist add it

var objects = [{y: 555}, {y: 444}]

for (var i = 0; i < maximum_number_objects_spawned; i++) {
  if (objects[i].y > game_height && !objects[i].lives_not_subtracted) {
    lives = lives - 1;
    objects[i].lives_not_subtracted = 'anyvalue';
  }
}
Related