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.