I am a newbie with coding and doing a collision detection project for my assignment. I think I got the Algorithm right but my problem is how will I access the object from my ArrayList I created and remove the object once collision is detected. Please see my code and help me to improve it to add the remove() from it. I added a boolean variable to check if true or false then do the remove function.
My end goal is to remove the ghost when it collides with the green ball
ArrayList<Greenball> array1 = new ArrayList<Greenball>();
ArrayList<Ghost> array2 = new ArrayList<Ghost>();
void setup(){
size(1000,500);
}
void draw(){
background(255);
for(int i = 0; i < array1.size() ; i++){
array1.get(i).move();
array1.get(i).display();
}
for (int i = 0; i < array2.size() ; i++){
array2.get(i).move();
array2.get(i).display();
}
}
void mousePressed(){
if (array1.size() != 5) array1.add(new Greenball(int(mouseX),int(mouseY), 40, 40)); //max at 5
}
void keyPressed(){
if (array2.size() != 5)array2.add(new Ghost(int(random(40,960)), int(random(40,460)), 40, 40)); //max at 5
class Ghost{
PImage ghost;
int x,y,w,h,xSpeed,ySpeed;
int pixelSize = 40;
Ghost(int x_, int y_, int w_, int h_){
x = x_;
y = y_;
w = w_;
h = h_;
xSpeed = int(random(-10,10));
ySpeed = int(random(1,10));
}
void move(){
x = x + xSpeed;
y = y + ySpeed;
if(x > width-pixelSize || x < 0){
xSpeed = xSpeed * -1;
}
if(y > height-pixelSize || y < 0){
ySpeed = ySpeed * -1;
}
}
void display(){
ghost = loadImage("greenghost.png");
image(ghost,x,y,w,h);
}
class Greenball{
PImage g;
int x,y,w,h,xSpeed,ySpeed;
int pixelSize = 40;
boolean alive=true;
Greenball(int x_, int y_, int w_, int h_){
x = x_;
y = y_;
w = w_;
h = h_;
xSpeed = int(random(-10,10));
ySpeed = int(random(1,10));
}
void move(){
x = x + xSpeed;
y = y + ySpeed;
if(x > width-pixelSize || x < 0){
xSpeed = xSpeed * -1;
}
if(y > height-pixelSize || y < 0){
ySpeed = ySpeed * -1;
}
}
void display(){
g = loadImage("green.png");
image(g,x,y,w,h);
}
void checkForCollision(Ghost ghost){
float d = dist(x,y,ghost.x,ghost.y);
float r1 = (x+y)/2;
float r2 = (ghost.x + ghost.y)/2;
if (d < r1 + r2) alive = false;
else alive = true;
}
}

