How do I stop an if-statement from carrying over to the next function

I would like the ball to bounce along the x-axis; the donut to bounce along the y-axis.

Currently the ball movement is fine.

The donut movement is following the if-statement for the ball as well as the donut.

How do I stop donut from executing the ball if-statement? And follow only the donut if-statement?

I tried using pushMatrix() / popMatrix() & then pushStyle() / popStyle above and below the code for displayBall(). And after reading the Processing Reference and seeing the results understand why this is not a viable solution.

***Please note, I’ll put the ball and donut each into their own class next.
But I want to understand how to stop code to carry over in an instance like this one.

float x = 0;
float y = 50;
int r = 25;
float speed = random(1, 3);

void setup() {
  size(400, 400);
}
void draw() {
  background(255);
  displayBall();
  displayDonut();
}

void displayBall() {

  noFill();
  strokeWeight(3);
  ellipse(x+r, 50, r*2, r*2);

  x = x + speed;
  if ((x >= width-r*2)||(x < 0)) {
    speed = speed *-1;
  }
}

void displayDonut() {

  noFill();
  strokeWeight(3);

  ellipse(x+(r*2), y, r*4, r*4);
  ellipse(x+(r*2), y, r*2, r*2);

  y = y + speed;
  if ((y >= height-r*2)||(y < r*2)) {
    speed = speed *-1;
  }
}
1 Like

It is nothing to do with the if statement, both the ball and donut use the same variable x for their horizontal position.

2 Likes

Change the code in the displayDonut() method to

  ellipse(r*2, y, r*4, r*4);
  ellipse(r*2, y, r*2, r*2);
1 Like

Thank you @quark! That worked! :slight_smile:

But now the ball is not going all the way to the right edge.
I’ve tried a few calculations with width / and radius, latest below:

void displayBall() {

  noFill();
  strokeWeight(3);
  ellipse(x+r, 50, r*2, r*2);

  x = x + speed;
  if ((x >= width - r)||(x < 0)) {
    speed = speed *-1;
  }
}

But no luck. What am I overlooking here?

Nevermind. I figured it out.

For others that might be interested it was the variable speed was reversed in the displayDonut method before the ball reached the right hand side. I don’t know how you solved it but here is mine :smile:

float x = 0;
float y = 50;
int r = 25;
float speedX, speedY;

void setup() {
  size(400, 400);
  speedX = speedY = random(1,3);
}

void draw() {
  background(255);
  displayBall();
  displayDonut();
}

void displayBall() {

  noFill();
  strokeWeight(3);
  ellipse(x + r, 50, r*2, r*2);

  x = x + speedX;
  if ((x > width - 2*r) || (x < 0)) {
    speedX = speedX * -1;
  }
}

void displayDonut() {

  noFill();
  strokeWeight(3);

  ellipse(r*2, y, r*4, r*4);
  ellipse(r*2, y, r*2, r*2);

  y = y + speedY;
  if ((y >= height-r*2)||(y < r*2)) {
    speedY = speedY *-1;
  }
}
2 Likes

Many thanks @quark for your help!