This is probably a really basic problem but I can’t seem to find any other articles on it.
Anyway, I have written a small bouncing ball program in Java to try and expand my basic skills. The program is just a simple bouncing ball that will drop and hopefully bounce for a while. The original program worked fine but now I have tried to add gravity into the program. The gravity actually works fine for a while but then once the bounces get really small the animation becomes erratic for a very short time then the position of the ball just constantly decreases. I’ve tried to figure out the problem but I just can’t see it. Any help would be most welcome.
public final class Ball extends Rectangle { float xspeed = 1.0f; float yspeed = 1.0f; float gravity = 0.4f; public Ball(float x, float y, float width, float height) { super(x, y, width, height); } public void update(){ yspeed += gravity; move(xspeed, yspeed); if(getX() < 0){ xspeed = 1; } if(getX() + getWidth() > 320){ xspeed = -1; } if(getY() < 0){ yspeed = 1; } if(getY() + getHeight() > 200 && yspeed > 0){ yspeed *= -0.98f; } if(getY() + getHeight() > 200 && yspeed < 0){ yspeed *= 0.98f; } } public void move(float x, float y){ this.setX(getX()+x); this.setY(getY()+y); }
}
EDIT: Thanks that seems to have sorted the erratic movement. I’m still struggling to see how I can stop my ball moving down when it has stopped bouncing. Right now it will move stop bouncing then continue moving down passed the ‘floor’. I think it’s to do with my yspeed += gravity line. I just can’t see how I’d go about stopping the movement down.
When you do
you are assuming that the ball has space move through a distance dx = v_i * t + 1/2 (-g) t^2. When you are very near the floor this may not be true. It fail if:
This bug causes your simulation to stop conserving energy, resulting in the erratic behavior you see at low amplitude.
You can reduce the problem by using smaller time steps, and you can get rid of it outright if you do test computation to notice when you’re out of room and to select a safe time step for that iteration (i.e. always use your default unless there is a problem, then calculate the best time step).
However, the basic approximation you’re using here has other problems as well. Look in any numeric analysis text for a discussion of solving differential equations numerically.