I could not find how to ask so there is a demo at the link. I am pretty sure this is a simple question but I can not seem to find why.
My question is: Why the ball stops bouncing? Is it about something like rounding in multiplications or divisions etc...
void move() {
PVector v0 = v;
PVector dv = PVector.mult(a, deltaT);
v.add(dv);
PVector d = PVector.add(
PVector.mult(v0, deltaT),
PVector.mult(dv, deltaT * 0.5));
move(d.x, d.y);
}
void move(float dx, float dy) {
p.x += dx;
p.y += dy;
if (p.x > width - r) {
p.x = width - r;
v.x = -v.x;
}
if (p.x < r) {
p.x = r;
v.x = -v.x;
}
if (p.y > height - r) {
p.y = height - r;
v.y = -v.y;
}
if (p.y < r) {
p.y = r;
v.y = -v.y;
}
}
It's an issue with this part of the code:
if (p.y > height - r) {
p.y = height - r;
v.y = -v.y;
}
Imagine that height is 600 and r is 10. When the ball hits the bottom (p.y > (600 - 10)) it gets reset to (600-10). But the ball can hit the bottom below that: p.y can be higher than height, leading to the issue you're having. The correct code in this case would then be:
if (p.y > height - r) {
p.y = (p.y - height) + (height - r);
v.y = -v.y;
}
Being (p.y - height) what you're losing each time the ball bounces.
Hope this helps.