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
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;
}
}``
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())
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).
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