I have a meteor and when there is only one meteor the collision works, but when I add more meteors the collision stops working, which prevents health form from getting subtracted.
I tried to search on the internet, but I did not get any good answers. I also asked on some forms and they said I have to create a place to store all the meteors and then check if there are any collisions.
let x = 200;
let x1 = 258;
let score = 0;
let health = 5;
let meteors = [];
let ecllipseMeteors = [];
let meteor;
let ecllipseMeteor;
let spaceShipimg;
let meteorimg;
let levels = 5;
function Meteor() {
this.x = random(0,600);
this.y = random(-200,-190);
this.speed = random(3,10);
this.fall = function() {
this.y = this.y + this.speed;
if (this.y > height) {
this.y = random(-200,-100);
this.speed = random(3, 7);
}
};
this.show = function() { image(meteorimg,this.x,this.y, 40, 40) };
}
function meteormodel() {
this.x = random(0,600);
this.y = random(-200,-190);
this.speed = random(3,10);
this.fall = function() {
this.y = this.y + this.speed;
if (this.y > height) {
this.y = random(-200,-100);
this.speed = random(3, 7);
}
};
this.show = function() { ellipse(this.x,this.y, 20, 20) };
}
function level() {
if (score == 10){
levels = 25;
}
}
function setup() {
createCanvas(600, 400);
timer = createP('');
for (let i = 0; i<5; i++) {
meteors[i] = new Meteor();
ecllipseMeteors[i] = new meteormodel();
}
meteor = new Meteor();
ecllipseMeteor = new meteormodel();
interval = setInterval(scoreCount, 500);
}
function gameOver() {
textSize(20);
text("GAME OVER YOUR SCORE: " + score, 200, 200);
fill(255);
}
function preload() {
spaceShipimg = loadImage('assets/spaceShip.png');
meteorimg = loadImage('assets/meteor.png');
}
function scoreCount() {
score++;
}
function draw() {
background(11, 72, 170);
//console.log(meteor)
hit = collideRectCircle(x1, 335, 20, 30, meteor.x, meteor.y, 40);
if(hit == true) {
health -= 1;
meteor.y = height+1;
if (health == 0) {
gameOver();
noLoop();
}
}
if (keyIsDown(LEFT_ARROW) && x > -46) {
x -= 5;
}
if (keyIsDown(RIGHT_ARROW) && x < 508) {
x += 5;
}
if (keyIsDown(LEFT_ARROW) && x1 > 9) {
x1 -= 5;
}
if (keyIsDown(RIGHT_ARROW) && x1 < 565) {
x1 += 5;
}
rect(x1, 335, 20, 30)
image(spaceShipimg,x,260,120,120)
for (let meteor of meteors) {
meteor.fall();
meteor.show();
}
textSize(20);
text("Health: " + health, 10, 20);
fill(255);
textSize(20);
text("Score: " + score, 10, 40);
fill(255);
}
I am expecting collision between meteor a spaceship-like it is with only one meteor.