Trouble with bouncing ball

Hi, so far I just have a ball bouncing on the screen, but the sketch stops working when I add the number 125 into the - if (y <= 125), part of my code, although it works when I have 100 instead of 125.

Can anyone explain to this me?

Thanks in advance :slight_smile:

int y = 100;
int ySpeed = 5;

void setup() {
  size(600, 400);
}

void draw() {
  background(0);
  fill(255, 0, 0);
  ellipse(width/2, y, 50, 50);
  
  y = y + ySpeed;
  
  if (y >= height-25) {
    ySpeed = ySpeed * -1;
  }
  
  if (y <= 125) {
    ySpeed = ySpeed * -1;
  }
  
}``
1 Like

Try

ySpeed = abs(ySpeed);

That’s always positive and not going back and forth. (The “abs” means “absolute” and just cuts off the minus sign, so it’s always positive. A positive number stays positive. See reference for abs())

2 Likes

Thanks! :slight_smile:

Hi,

I found that 105 was the point where it did a song and dance; you can figure out why examining your code.

The abs() as @Chrisir suggested is the key; your code was toggling it and may not have been always in the expected state (but in the programmed state).

Then you define direction -1 or +1.

Also useful for troubleshooting to see state of variables in code:
https://processing.org/reference/print_.html
https://processing.org/reference/println_.html

:slight_smile:

3 Likes

Thanks for the reply! :slight_smile: I think I get it

Yeah, we could say after the if-clause applied and speed changed its direction, the ball was still inside that area so the condition still applied and the direction was changed again and so on.

We see this as a stutter.

Now with abs() the direction is just set as we want it and can’t go back and forth

You might change your other if clause too

My first reply was wrong - I had -1 there

Corrected it

Apologies