Search code examples
libgdxgame-physics

I have an array of blasts and an array of zombies, how can I efficiently detect collisions?


I have an array of blasts, and an array of zombies, but I'm struggling to find a way to efficiently detect collisions and remove both the blasts and zombies that have collided. Any suggestions?

    Iterator<Rectangle> blastIter = blasts.iterator();

    while(blastIter.hasNext()) {
        Rectangle blast = blastIter.next();
        blast.x += 200 * Gdx.graphics.getDeltaTime();
        if(blast.x + 16 > 800) blastIter.remove();
    }

    Iterator<Rectangle> zombieIter = zombies.iterator();

    while(zombieIter.hasNext()) {
        Rectangle zombie = zombieIter.next();
        zombie.x -= 150 * Gdx.graphics.getDeltaTime();
        //if(zombie.overlaps(blast)) zombieIter.remove();
    }

Solution

  • You need to put the other iterator inside of the other iterator, try this:

    Iterator<Rectangle> zombieIter = zombies.iterator();
    
    while(zombieIter.hasNext()) {
    
        Rectangle zombie = zombieIter.next();
        zombie.x -= 150 * Gdx.graphics.getDeltaTime();
    
        Iterator<Rectangle> blastIter = blasts.iterator();
    
        while(blastIter.hasNext()) {
    
            Rectangle blast = blastIter.next();
            blast.x += 200 * Gdx.graphics.getDeltaTime();
    
            if(blast.x + 16 > 800) blastIter.remove();
            if(zombie.overlaps(blast)) zombieIter.remove();
    
        } 
    }