Bouncing Ball in Java

This is probably really the main issue, but I cannot find any other articles.

In any case, I wrote a small program for a bouncing ball in Java to try to expand my basic skills. A program is just a simple bouncing ball that will fall and hopefully bounce for a while. The original program worked fine, but now I tried to add gravity to the program. Gravity actually works fine for a while, but after the bounces become very small, the animation becomes unstable for a very short time, then the position of the ball is constantly decreasing. I tried to figure out the problem, but I just can't see it. Any help would be appreciated.

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: , , , . , , . -, , "". , yspeed + = . , .

+3
5

yspeed += gravity;

, , dx = v_i * t + 1/2 (-g) t ^ 2. , . , :

  • .
  • (, ).

, , , .

, , , , , (.. , , ).

, , . .

+3

, , , "", - () , - , .

, , - :

    if(getY() + getHeight() > 200){
            yspeed *= -0.981;
            setY(200 - getHeight());
    }
+1

: y-speed 1, , , yspeed -yspeed ( , ).

-, -0.981 , 0.4, . , , , , .

, y , :

if (getY() + getHeight() + yspeed > 200) {
    move(xspeed, 200 - getY() - getHeight());
} else {
    move(xspeed, yspeed);
}
+1

, ,

yspeed *= -0.981;

. , , ( 0.981 < 1.0) , . :

if(getY() + getHeight() > 200){
  yspeed *= -0.981;
  setY(400 - getY() - getHeight()); // I believe this is right.
}

, , , .

+1

[EDIT: , , , , :))

if(getY() + getHeight() > 200){
  yspeed *= -0.981;
}

You deny vertical speed with every update. I'll probably try to handle gravity in slices with update sizes. Assuming you are doing 30 updates per second (for 30 frames per second), maybe something like

// Define some constants
SecondsPerUpdate = (1.0f / 30);
AccelDueToGravity = 0.981;

if(getY() + getHeight() > 200){
  yspeed -= (AccelDueToGravity * SecondsPerUpdate);
}
+1
source

Source: https://habr.com/ru/post/1704176/


All Articles