In my game engine, there are Particles, all of these particles have a slightly different lifespan. Every update, their life is shortened and when it reaches 0 it is removed from an ArrayList meaning it will no longer be updated or rendered. Although under normal game play I experience no problems with this approach, when I have a large large number of particles (around 100,000) there is major lag when creating and removing (but not updating) the particles.
Because of that lag, I am looking to improve the efficiency of this setup. I have tried only removing so many per update and leaving the rest for the next update but that didn't provide too great of results.
package com.burksnet.code.games.rain.entity.particle;
import com.burksnet.code.games.rain.entity.Entity;
import com.burksnet.code.games.rain.graphics.Screen;
import com.burksnet.code.games.rain.graphics.Sprite;
import com.burksnet.code.games.rain.level.Level;
public class Particle extends Entity {
private Sprite sprite;
private int life;
private double speed = 2;
public static int maxParticleCount = 2500000;
protected double xa, ya;
//Life is how long it lives, x, y, and level are obvious.
public Particle(int x, int y, int life, Level level) {
super(level);
//The sprite to be rendered.
sprite = Sprite.particleNormal;
this.x = x;
this.y = y;
this.life = life;
//how it will move. effectively randomly.
this.xa = random.nextGaussian() /2 * speed;
this.ya = random.nextGaussian() /2 * speed;
}
//Renders the particle on screen.
public void render(Screen screen) {
if(life <= 0 ) return;
screen.renderSprite(x, y, sprite, true);
}
//Updates it.
public void update() {
if(life <= 0 ){
//Removes the item from the level, making it no longer be rendered or updated. See the method below.
level.remove(this);
}
this.x += xa;
this.y += ya;
life--;
}
}
Level.remove(Particle e) below
public void remove(Particle e) {
particles.remove(e);
}
Level.add(Particle e) below. Is used when a particle is created so it may be updated and rendered.
public void add(Particle e) {
particles.add(e);
}
I guess it is definitely possible this is just a pure limitation that cannot be overcome but I hope that is not the case.