Juggling Game Bug

Hello, I am experiencing a weird bug in my game where the ball seems to get caught in a conditional that throws it out of my display screen. I am not really sure why this is happening because my logic seems to be correct. The game is supposed to be like juggling where you try to survive with a score above 0 as long as possible. Let me know if you have any ideas on why this might be happening.

ball b1;
ball b2;
int score = 0;
void setup(){
  size(500,500);
  b1 = new ball(random(0,width),random(0,height),1,1,color(random(0,255),0,random(0,255)),40);
  b2 = new ball(random(0,width),random(0,height),1,1,color(random(0,255),0,random(0,255)),40);

}

void draw(){
  background(255);
  
  textSize(20);
  fill(0);
  text("Score:" +score,20,40);
  b1.display();
  b1.move();
  b1.edges();
  b2.display();
  b2.move();
  b2.edges();
  b1.score();
  b2.score();
  //b1.miss();
  //b2.miss();
}
// Classes start with a capital letter. 
class ball{
  float x;
  float y;
  float dx;
  float dy;
  color rcolor;
  float size = 40;
  
  ball(float x, float y, float dx, float dy,color rcolor, float size){
    this.x=x;
    this.y=y;
    this.dx=dx;
    this.dy=dy;
    this.rcolor=rcolor;
    this.size=size;
  }

void display(){
  fill(rcolor);
  circle(x,y,size);
}

void move(){
  x=x+dx;
  y=y+dy;
}

void edges(){
   if(x>width || x<0){
     if(dx>0){
       dx-=0.5;
     }
   else{
      dx+=0.5;
   }
  dx = dx *-1;
  score--;  
 }

 
  
  else if (y>height || y<0){
    if(dy>0){
    dy -=0.5;
    }
    else{
    dy+=0.5;
    }
  dy = dy *-1;
  score--;

}
}

void score(){
  if(mousePressed && mouseX>=x-size/2 && mouseX<=x+size/2 && mouseY>=y-size/2 && mouseY<=y+size/2){
    dy= abs(dy)+0.5;
    dx= abs(dx)+0.5;
    //Only goes faster when x and y cords increase
    rcolor = color(random(0,255),0,random(0,255));
    score = score +5;
}
}

}
1 Like

Shouldn’t this be inside the if clause?

It’s Ball with a capital B :wink:

1 Like

it seems to be happening when the ball hits a corner

my apologies.

Anyway, you check both edges at one time:

   if(x>width || x<0){

This can lead to errors!

I always change this and test separately :

   if(x>width){

  if(x<0){

then the what you do is :

   if(x>width){
      dx = - abs (dx); // always neg !!

  if(x<0){
      dx = abs (dx); // always pos !!


That’s better!

Chrisir

2 Likes