2
\$\begingroup\$

I have two groups of randomly generated actors, one is bullets second is enemies. And as of now I have no idea how to check collision of randomly genrated actors and remove the overlaped actors. I'm newby.

At least provide some pseudocode! Thanx in advance!!!

\$\endgroup\$
2
  • \$\begingroup\$ I suggest starting by looking at Rectangle.overlaps(). \$\endgroup\$ – Kelly Thomas Nov 28 '14 at 11:32
  • \$\begingroup\$ Actually I previously used Rectangle. Overlaps(), but I dont have any idea how to apply it on randomly generated actors. \$\endgroup\$ – Khusrav Nov 28 '14 at 11:43
6
\$\begingroup\$

First ensure that your Actors are able to report their bounds:

public class Enemy extends Actor {

    Rectangle bounds;
    public Enemy() {
        bounds=new Rectangle((int)getX(), (int)getY(), (int)getWidth(), (int)getHeight());
    }

    public Rectangle getBounds() {
        return bounds;
    }

    private void setXY(float pX,float pY) {
        setPosition(pX, pY);
        bounds.setX((int)pX);
        bounds.setY((int)pY);
    }
}

Then collect any Actors into ArrayLists:

//init lists
List<Enemy> enemies = new ArrayList<Enemy>();
List<Bullet> bullets = new ArrayList<Bullet>();

//add actors to lists
enemies.Add(new Enemy());
bullets.Add(new Bullet());

Now you can itterate though the lists and check for collisions:

for (int i = enemies.size() - 1; i >= 0; i--) {
    Enemy enemy = enemies.get(i);
    for (int j = bullets.size() - 1; j >= 0; j--) {
        Bullet bullet = bullets.get(j);
        if(enemy.getBounds().overlaps(bullet.getBounds())) {
            //handle collision
        }
    }
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Thanx a lot, I'm new here so can't give you +1 else you deserve it!!! \$\endgroup\$ – Khusrav Nov 28 '14 at 12:07
  • 1
    \$\begingroup\$ but a nested for() loop is terrible for performance - is this really the only way ? \$\endgroup\$ – Someone Somewhere Nov 25 '15 at 12:02
  • 2
    \$\begingroup\$ @SomeoneSomewhere This approach was chosen for its simplicity. If you are more concerned about performance then you might want to consider a quad tree. \$\endgroup\$ – Kelly Thomas Nov 26 '15 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.