Help with collision between two array objects

I’m a beginner coder learning in Processing and I’m trying to figure out how I can detect a collision between two array objects so that both objects can no longer display on the screen.

The game is a shooter game, but I tried to simplify the code as much as I could. Any help would be greatly appreciated.

//arrays
Meteor[] meteor = new Meteor[10];
ArrayList<Bullet> bullets;

//variables
float rectX = 300;
int speed = 1;
int meteorW = 90;
int bulletChange = 3;
int meteorXMin = 50;
int meteorXMax = 550;
int bulletWidth = 10;
int bulletHeight = 25;
int bulletYStart = 730;

//image
PImage meteors;

void setup() {
  size(600, 800);
  
  //meteors
  for(int i = 0; i < meteor.length; i++) {
    meteor[i] = new Meteor(random(meteorXMin, meteorXMax), random(-2 * height));
    
  //bullets
   bullets = new ArrayList<Bullet>();
   bullets.add(new Bullet(width/2, 0, bulletWidth, bulletHeight));
  }
  
  //load and resize image
  imageMode(CENTER);
  meteors = loadImage("meteor.png");
  meteors.resize(meteorW, meteorW); 
}

void draw() {
  background(0);
  
  //meteor objects
    for(int i = 0; i < meteor.length; i++) {
    meteor[i].drawTheMeteors();
    meteor[i].moveTheMeteors();
  }
  
  //bullet objects
  for (int i = bullets.size()-1; i >= 0; i--) { 
    Bullet bullet = bullets.get(i);
    bullet.moveTheBullets();
    bullet.displayTheBullets(); 
  }  
}

void mousePressed() {
  bullets.add(new Bullet(rectX, bulletYStart, bulletWidth, bulletHeight));
}

class Bullet {
  float x;
  float y;
  float speed;
  float w;
  float h;
  float life = 255;
  
  Bullet(float tempX, float tempY, float tempW, float tempH) {
    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speed = 3;
  }  

  void moveTheBullets() {
    y = y - speed;
  }
  
  void displayTheBullets() {
    fill(255, 0, 0);
    ellipse(x, y, w, h);
  }
}

class Meteor {
  float x;
  float y;
  float speed = 1;
  
  Meteor(float tempX, float tempY) {
    x = tempX;
    y = tempY;
  }
  
  void drawTheMeteors() {
    image(meteors, x, y);
  }
  
  void moveTheMeteors() {
    y = y + speed;
  }
}
1 Like

Hello @maverick24,

You will need to check the distance between objects. And this can be done with the dist() function. Excellent tutorial here by Abe Pazos on youtube on how to use:

Also, I recommend looking in reference section of processing.org site.
As well as this example in the examples section for slightly more advanced implementation:
https://processing.org/examples/circlecollision.html

:nerd_face:

2 Likes