# 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?

``````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!

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

3 Likes

Thanks for the reply! 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