I’m looping through an ArrayList to check if an enemy is colliding with one of the player’s bullets. It runs smoothly with only a few enemies on the screen but when there’s a bunch of them then the game starts to lag because every enemy is looping through every bullet.
Code:
public void checkCollision(ArrayList<ShipBullet> bullets){
for (int i = 0; i < bullets.size(); i++){
ShipBullet bul = bullets.get(i);
Rect rect1, rect2;
rect1 = new Rect(bul.x,bul.y,bul.x+1,bul.y+4);
rect2 = new Rect(x, y, x+graphic.getWidth(), y+graphic.getHeight());
if (rect1.intersect(rect2)){
destroyed = true;
break;
}
}
}
Is there any better way of doing this? I was thinking of pooling the bullets but I’m not familiar with pooling just yet (pretty much just found it on Google). Just wondering if there are other methods that I can try.
The method is checked every frame and there can be up to 10~ bullets on the screen from the player alone. And it starts lagging when 6 or so enemies are present. Not to mention I’m working on a cheap Android device but I’d still like to optimize it.
Thanks!