In this program I simulate the gravity. All works but when there is no more movement for the ball it keep bouncing 1-5 pixels depending on the gravity value I set. How could i stop the ball when the energy is lost? I want the xSpeed to become 0 and the ball to stay on a fix position.
Edit: The gravity variate from 1 to 100. The user can change the gravity.
energyLoss = 0.9 and dt = 0.2
// right and left wall collision
if (x + xSpeed > this.getWidth() - radius - 1) {
x = this.getWidth() - radius - 1;
xSpeed = -xSpeed;
} else if (x + xSpeed < 0 + radius) {
x = 0 + radius;
xSpeed = -xSpeed;
} else
x += xSpeed;
if (y == this.getHeight() - radius - 1) {
}
if (y > this.getHeight() - radius - 1) {
y = this.getHeight() - radius - 1;
ySpeed *= energyLoss;
ySpeed = -ySpeed;
// friction with the ground
xSpeed *= xFriction;
if (Math.abs(xSpeed) < .4)
xSpeed = 0;
} else {
ySpeed += gravity * dt; // velocity formula
y += ySpeed * dt + .5 * gravity * dt * dt; // position formula
}
repaint();
The simplest way to fix this problem is to detect a special case where the ball is on the wall with 0 (or very small) Y velocity. This is basically what DwB is suggesting.
However, you then need to go further and make sure that you stop applying gravity when you’re in that situation.
Something like this: