Time interval between movement/shooting

Hey!
So my enemys can move and they can shoot. But they do it on the same time.
Do you know how I could do it that there is a small delay between them?

Here you can watch:

This is my method for the enemys to shoot:


// Time Interval
      if(enemyCount>125)
      {
          for(int enemys = 0;enemys < enemyContainer.size(); enemys++) // Go throught all enemys
          {
             for(int bullets = 0;bullets < 5;bullets++) // Shoot 5 Bullets
             {
                 projectile = new Projectile(enemyContainer.get(enemys).x - (bullets*30),enemyContainer.get(enemys).y + 13,sprites.projectile);  // Create new Projectile
                 enemyBullets.add(projectile);  // Add the bullet the Container
             }
            
          }
          enemyCount=0;  
      }
      else enemyCount++;

Ok, I think this is probably the crappiest, less cpu-friendly solution ever. I’m still a n00b and this was the first thing that came to my mind:



//Code...

int randomness = 30; //If you increase this number, the enemies will shoot less times

Random ran = new Random(); //Creates a new random number generator

//Code...

// Time Interval
      if(enemyCount>125)
      {
          for(int enemys = 0;enemys < enemyContainer.size(); enemys++) // Go throught all enemys
          {
              if(ran.nextInt(randomness) == 0) //This means that this enemy will not shoot unless the random number equals 0 (or whatever value you want)    
              {
                 for(int bullets = 0;bullets < 5;bullets++) // Shoot 5 Bullets
                 {
                     projectile = new Projectile(enemyContainer.get(enemys).x - (bullets*30),enemyContainer.get(enemys).y + 13,sprites.projectile);  // Create new Projectile
                     enemyBullets.add(projectile);  // Add the bullet the Container
                 }
              }
          }
          enemyCount=0;  
      }
      else enemyCount++;

Use H3rnst’s code for random shooting ("== 0" is probably extremely little, you should make it like “< 5” at least).

It is also best to handle shooting inside the Enemy class instead and in the constructor, create a random offset:


private long tickCount;

public Enemy(....) {
    ....
    
    tickCount = (long)(Math.random() * 126); //0 - 125
}

...

public void update() {
    if(tickCount > 125) {
        for(int bullets = 0; bullets < 5; bullets++)
            getParent().getEnemyBulletList.add(new Projectile(....));
        
        tickCount = 0;
    }
    else
        tickCount++;
}

Great! Thank you it work fine. :wink: