I’m making a game, in which when the asteroid hits the spaceship the image should be portrayed on the screen. Below the whole code I pasted a loop, which is wrong and I have no idea how to fix it in order to make the intersection correct.
how can I make the intersection loop correctly?
Asteroids[] asteroids = new Asteroids[12];
Spaceship spaceship = new Spaceship();
int totalAsteroids = asteroids.length;
PImage img;
void setup() {
size(640, 360);
background(255);
spaceship = new Spaceship();
for (int i = 0; i < totalAsteroids; i++) {
asteroids[i] = new Asteroids();
}
img = loadImage("youdied.jpg");{
size(480, 270);
img.resize(480,270);
}
}
void draw() {
spaceship.display();
spaceship.move();
for (int i = 0; i < totalAsteroids; i++ ) {
if (asteroids[i].reachedBottom()) {
asteroids[i] = new Asteroids();
}
asteroids[i].move();
asteroids[i].display();
}
}
class Asteroids {
float x, y; // Variables for location of raindrop
float speed;
color c;
float r; // Radius of raindrop
Asteroids() {
r = 15; // All raindrops are the same size
x = random(width); // Start with a random x location
y = -r*4; // Start a little above the window
speed = random(2, 6); // Pick a random speed
c = color(100); // Color
}
void display() {
// Display the drop
fill(c);
noStroke();
for (int i = 4; i < r; i++ ) {
ellipse(x, y + i*2, i*2, i*2);
}
if ((mouseX-15 <= asteroids.x && asteroids.x >= mouseX + 15)) {
if ((mouseY - 15 <= asteroids.x && asteroids.x >= mouseY + 15)){
image(img, 0, 0);
for (int f = 0; f< asteroids.x; f++){
asteroids[f].display();
}
}
else{
r = r+0.1;
}
}
}
boolean reachedBottom() {
// If we go a little beyond the bottom
if (y > height + r*4) {
return true;
} else {
return false;
}
}
void move() {
// Increment by speed
y += speed;
}
}
class Spaceship {
float k; float l; float easing = 0.2;
int b=100; int c=color(0, 255, 0);
Spaceship() {
}
//display the spaceship
void display() {
background(0);
ellipseMode(CENTER);
noStroke();
fill(c);
ellipse(k, l, b/1.3, b/3);
ellipse(k, l-b/6, b/4, b/4);
fill(150);
stroke(0);
ellipse(k-b/5, l, b/10, b/10);
ellipse(k-b/5, l, b/10, b/10);
ellipse(k, l, b/10, b/10);
ellipse(k+b/5, l, b/10, b/10);
}
void move() {
float targetX = mouseX;
float dk = targetX - k;
k += dk * easing;
float targetY = mouseY;
float dl = targetY - l;
l += dl * easing;
}
}
this loop is the one where error occurs:
if ((mouseX-15 <= asteroids.x && asteroids.x >= mouseX + 15)) {
if ((mouseY - 15 <= asteroids.x && asteroids.x >= mouseY + 15)){
image(img, 0, 0);
for (int f = 0; f< asteroids.x; f++){
asteroids[f].display();
}
}
else{
r = r+0.1;
}
}
}