Search code examples
javaandroidlibgdxtile2d-games

Spawning Enemies From ArrayList


I have twelve enemies in an ArrayList and I want to delay the batch.draw for each enemy. I tried the following code in the render method but it just makes the sprites flicker. I am using libgdx. Please help ;(

for (int i = 0; i < list.size(); i++)
{
    fireDelay -= Gdx.graphics.getDeltaTime();
    if (fireDelay <= 0)
    {
        batch.draw(list.get(i)//..etc)                    
        fireDelay += 0.2;
    }
}

Solution

  • The following code will definitely work:

    boolean spawnTime=0;
    
    void spawnEnemy(){
      Rectangle rect = new Rectangle();
      rect.x = Gdx.graphics.getWidth()/2;
      rect.y = Gdx.graphics.getHeight();
      rect.setSize(50,50);
      myList.add(rect);
    }
    
    spawnTime+=Gdx.graphics.getDeltaTime();
    
    //call spawnEnemy function every second
    if(spawnTime>=1){
      spawnEnemy();
      spawnTime=0;
    }
    
    //draw all the rectangles to the batch you added in the list
    for(Rectangle rect: myList){
      batch.draw(rect,rect.x,rect.y,rect.w,rect.h);
    }
    

    Note: Declare spawnTime globally.