简体   繁体   中英

How to remove Sprite when collision is detected? Libgdx

Every random time (between 1,2 and 3 seconds) a rectangle and a sprite is created,1 rectangle for each sprite that spawns.

new enemy method is called at random time:

public void newEnemy(){
        Sprite enemy= Pools.obtain(Sprite.class);
        enemy.set(enemySpr);
        enemy.setPosition(200,150);
        enemies.add(enemy);}

the same thing happens to rectangles:

 public void newRect(){
        Rectangle rect=Pools.obtain(Rectangle.class);
        rect.set(enemyRect);
        rectangles.add(rect);
    }

basically when the rectangle and sprite are spawned they move upward,and at the top of the screen there's another rectangle.I wan't the rectangle and sprite to be removed when the collision is detected.

@Tenfour04 I just tried your advice but I still get the error.

while (enemyIterator.hasNext()){
            Sprite nextEnemy=enemyIterator.next(); //I get the error here..
           if(enemySpr.getY()+enemySpr.getHeight()>=treeObj.treeSpr.getY()){
               removeEnemy(nextEnemy);
           }

@Tenfour04 this is the error:

Exception in thread "LWJGL Application" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at com.dreamroad.savethetree.EnemyClass.update(EnemyClass.java:66)
    at com.dreamroad.savethetree.MyGdxGame.render(MyGdxGame.java:51)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

Process finished with exit code 0

You could put the stack trace, on the other side I do not know, that is, removeEnemy (...) and how it works, but maybe this helps:

 while (enemyIterator.hasNext()){

     Sprite nextEnemy=enemyIterator.next(); //I get the error here.. -> push stact trace

      if(enemySpr.getY()+enemySpr.getHeight()>=treeObj.treeSpr.getY()){

           enemyIterator.remove();
           //removeEnemy(nextEnemy);
       }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM