Please plese please help me with my problem, appearing in a simple p5.js code

https://editor.p5js.org/Nis_Collect/sketches/U0p3GjOK1

The above provided link is of my project in which I want to make only one rectangle appear after particular frame-counts.But there appears a problem while doing this. When I run the code, the first very rectangle gets generated properly but the rectangle which are to appear after the very first one, gets something wrong with it.
I think that’s because my loop gets running infinitely ,but I am not sure with this.
I can’t figure out what’s getting wrong can someone please help me with this.

1 Like

Hello @Nis,

In draw the code loops through every small enemy, updating them and rendering them to the screen. Each iteration of that loop, the program checks if it’s time to generate new small enemies, and once every 1.5 seconds (roughly), that is what happens.

The first time, when there’s only one small enemy, one new small enemy will be generated. Next time, there are two enemies on the screen, and two new ones will be created. The third time, four new small enemies will be created. And so on. You will end up with lots of enemies. :slight_smile:

My suggestion is that you move the generation of new enemies outside the for loop. Also, maybe there’s a good idea to cap the maximum amount of enemies in some way? Only generate new enemies if there’s less than 100 on-screen, or similar.

  for (var i = 0; i < SmallEnemy.length; i++) {
    SmallEnemy[i].show();
    SmallEnemy[i].update();

    // The enemy generation below should probably move outside
    // this for loop.
    if (frameCount % 100 == 0) {
      SmallEnemy.push(new smallEnemy());
      print(" came in");
    }
  }
2 Likes

Thank you so so much, Sir.
Your idea worked…
I asked the questions at many platforms but no one’s answer was as proper and good as your’s.
Now I am your fan…
Please accept me as your fan, sir.