I am trying to make a game the sends squares at you and you have to avoid them by moving your mouse that controls a circle around them.
I added a lives value to add more to the game, and set up collision detection so that as soon as the distance from the middle of the circle to the square was less than the radius of the circle, it took away a life. This collision detection works, it's just that in my if statements that detect collision I added "lives = lives - 1;", but as soon as they collide, the lives value drops instantly to 0.
float centerY = 250;
float centerX = 175;
float lives = 3;
float rectY1 = random(0,500);
float rectX1 = random(0,500);
float rectY2 = random(0,500);
float rectX2 = random(0,500);
float rectY3 = random(0,500);
float rectX3 = random(0,500);
float rectY4 = random(0,500);
float rectX4 = random(0,500);
float rectY5 = random(0,500);
float rectX5 = random(0,500);
float rectY6 = random(0,500);
float rectX6 = random(0,500);
int score = 0;
int squareRadius = 15;
void setup(){
size(500,500);
background(155);
}
void draw(){
boolean gameOver = false;
boolean lifeLost = false;
background(155);
fill(149,185,215);
ellipse(centerX,centerY,30,30);
centerX = mouseX;
centerY = mouseY;
fill(0);
rect(rectX1,rectY1,30,30);
rect(rectX2,rectY2,30,30);
rect(rectX3,rectY3,30,30);
rect(rectX4,rectY4,30,30);
rectX1 = rectX1 - 5;
rectX2 = rectX2 - 5;
rectX3 = rectX3 - 5;
rectX4 = rectX4 - 5;
rectX5 = rectX5 - 5;
if(rectX1 + 30 < 0){
rectX1 = 500;
rectY1 = random(0,600);
score = score + 1;
}
if(rectX2 + 30 < 0){
rectX2 = 500;
rectY2 = random(0,600);
score = score + 1;
}
if(rectX3 + 30 < 0){
rectX3 = 500;
rectY3 = random(0,600);
score = score + 1;
}
if(rectX4 + 30 < 0){
rectX4 = 500;
rectY4 = random(0,600);
score = score + 1;
}
if(rectX5 + 30 < 0){
rectX5 = 500;
rectY5 = random(0,600);
score = score + 1;
}
if(dist(mouseX,mouseY,rectX1,rectY1) < 30){
lifeLost = true;
}
if(dist(mouseX,mouseY,rectX2,rectY2) < 30){
lifeLost = true;
}
if(dist(mouseX,mouseY,rectX3,rectY3) < 30){
lifeLost = true;
}
if(dist(mouseX,mouseY,rectX4,rectY4) < 30){
lifeLost = true;
}
if(lifeLost == true){
lifeLost = false;
lives = lives - 1;
}
if(lives == 0 || lives < 0){
gameOver = true;
}
text("Lives:",20,20);
if(lives == 3){
fill(255,0,0);
ellipse(60,15,10,10);
ellipse(80,15,10,10);
ellipse(100,15,10,10);
}
if(lives == 2){
fill(255,0,0);
ellipse(60,15,10,10);
ellipse(80,15,10,10);
}
if(lives == 1){
fill(255,0,0);
ellipse(60,15,10,10);
}
if(lives == 0){
text("Game over.",250,250);
}
fill(0);
if(gameOver == false){
text("Score: " + score,120,20);
}
else{
background(0);
text("Score: Game Over",120,20);
fill(255);
text("Game over. Press Space to continue.",150,250);
}
if(score > 50){
fill(0);
rect(rectX5,rectY5,30,30);
if(score > 50 && score < 60){
text("You have reached a score of 50. Adding another square.",100,250);
}
}
if(gameOver == true){
if(keyPressed){
if(key == 32){
gameOver = false;
lives = 3;
score = 0;
background(55);
}
}
}
}