How can I achieve removing objects within an ArrayList. I tried the following code but the particles don't die. I outputted the size of the removeQue ArrayList and it outputs 1. The checkCollide method works fine for detecting collisions.
This is within a Class named Particles
public void Update(){
for(Enemies e: Enemies.enemies){
if(this.checkCollide(e.x,e.y,e.mass)){
removeQue.add(this);
}
}
removeQue.clear(); // Remove objects
}
More specifications:
Here is the whole class:
import java.util.ArrayList; import java.awt.*;
public class Particle{
public static ArrayList<Particle> particles = new ArrayList<Particle>();
public static ArrayList<Particle> removeQue = new ArrayList<Particle>();
public static int particleCount;
private int x,y,r,g,b,mass;
private boolean playerParticle = false;
private Color color = new Color((int)Math.floor(Math.random() * 256),(int)Math.floor(Math.random() * 256),(int)Math.floor(Math.random() * 256));
public Particle(int x,int y, int mass, boolean p){
particleCount++;
this.x = x;
this.y = y;
this.mass = mass;
playerParticle = p;
}
public void Update(){
for(Enemies e: Enemies.enemies){
if(this.checkCollide(e.x,e.y,e.mass) && !playerParticle){
if(e.mass <= 200){
e.addMass(this.mass);
}
if(e.mass >= 200){
e.isTarget = false;
e.goalReached = true;
e.targetType = "c";
}
if(e.targetType.equals("p")){
e.goalReached = true;
e.isTarget = false;
}
this.x = (int) Math.floor(Math.random() * 10001);
this.y = (int) Math.floor(Math.random() * 10001);
}else if(this.checkCollide(e.x,e.y,e.mass) && playerParticle){
e.addMass(this.mass);
removeQue.add(this);
}
}
removeQue.clear();
}
private boolean checkCollide(double x,double y,double mass){
return x < this.x + 10 && x + mass > this.x && y < this.y + 10 && y + mass > this.y;
}
public void Draw(Graphics bbg){
bbg.setColor(color);
bbg.fillRect(x,y,10,10);
bbg.drawRect(x,y,10,10);
}
}
This is my main Update method
public void update(){
for(Particle p: Particle.particles){
p.Update();
}
for(Enemies e: Enemies.enemies){
e.Update();
}
}
removeQue.remove( Object o ), you can also remove using index if you know it by usingremoveQue.remove( index )