We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I wrote this simple piece of code and i can't find the reason why after a few bounces (5 or 6) the ball sticks to the bottom? just tried to find it out for hours
float x = 300;
float y = 0;
float speedx = 0;
float speedy =5.0;
float gravity = 0.2;
float r = 50.0;
void setup(){
size(600, 600);
smooth();
}
void draw(){
ball();
move();
bounce();
gravity();
}
void ball() {
ellipse(x, y, r, r);
}
void move () {
y=y+speedy;
}
void bounce() {
if((x>width)||(x<0)){
speedx=speedx*-1;
}
if((y>height)||(y<0)){
speedy=speedy*-0.95;
}
}
void gravity() {
speedy=speedy+gravity;
}
</pre>
Answers
post the code
posted the code, i had to find out how to format it.. sorry
you have to be careful with this. sometimes the y position is so far below the line before the bounce is detected that the -.95 velocity added on the next loop isn't enough to take it back above the line.
add println(y + " : " + speedy); after line 33 and see....
thank you that should be the problem.. but i don't get the difference to daniel shiffmans code which works:
This is what I've come up with: >:/
different combination of start values, that's all.
maybe he's chosen them because he knows they won't cause the issue, maybe he was lucky.
the way around this is to set the position of the ball after the bounce as far above the bottom as it was below the limit when the bounce was detected (11.518 here), minus some bounce coefficient. it's kinda complicated (and i'm just off out...)
thank you very much!
I always warn with code like
if (y > height - RAD | y < RAD) spdY *= -BOUNCE;
or
because
spdY *= -BOUNCE;
or
speed = speed * -0.95;
doesn't give a stable / reliable / robust result. Let me explain.
When the ball is too far outside the screen you mulitply it with BOUNCE (speed gets negative, good).
But (big one) when in the next iteration it is still outside the screen you again mulitply with BOUNCE and the speed gets positive where it should really remain negative. Thus the ball can stutter outside the screen (move up and down in one spot).
I always recommend
So the result is reliable and always negativ. Good. (Because abs() gives you the absolute (always positive) value of speed and when you multiply it with a negative value, the result is always negative.)
The line
if (y > height - RAD | y < RAD) spdY *= -BOUNCE;
we have to split into
@Chrisir thanks very much that you clarified this for me!
you are welcome!