Bouncing ball in Java

This may be a very basic question, but I can't seem to find any other articles

Anyway, I wrote a little bouncing ball program in Java, trying to expand my basic skills The plan is just a simple bouncing ball that will fall and hopefully rebound for some time The original program works normally, but now I've tried to add gravity to the program Gravity can actually work normally for a period of time, but once the bounce becomes very small and the animation becomes unstable in a short time, the position of the ball will continue to decrease I tried to find out the problem, but I just couldn't see it Any help is 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);
}

}

Editor: Thank you. It seems that the erratic movement has been sorted I'm still trying to see how I can stop my ball from moving down when it stops bouncing Now it will stop bouncing and continue to move down through the floor I think this is related to my yspeed = gravity line I just can't see how to stop moving

Solution

When you do

yspeed += gravity;

You assume that the ball has space to move DX = v_ i * t 1/2(-g)t ^ 2. This may not be true when you are very close to the floor It will fail if:

>You're close enough to the floor to move down > you're very close to the floor and slow (like the ball loses most of its energy)

This error causes your simulation to stop saving energy, resulting in unstable behavior you see at low amplitude

You can reduce the problem by using smaller time steps, if you do a test calculation to pay attention when you leave the room and select a safe time step for the iteration (that is, you can get rid of it completely if you always use your default value), then calculate the best time step)

However, there are other problems with the basic approximation you use here View any numerical analysis text for a discussion of numerically solving differential equations

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>