Bouncing Ball Animation 2/3

23 Views Asked by At

I am trying to make a ball animation where each bounce after the first one is reduced to 2/3 in terms of bounce height.

I tried changing the ySpeed variable, but that only reduced how fast the drop was. I also tried changing the y variable, but they did not output what I was expecting. There is also an issue with the ball flickering.



import java.awt.*;
import java.awt.event.*;

public class BallFrame extends Frame {
    private int x = 10;
    private int y = 100;
    private int xSpeed = 1;
    private int ySpeed = 10;
    private static final int BALL_SIZE = 30;
    private boolean isRunning = false;

    public BallFrame() {
        setTitle("Bounce Bounce");
        setSize(500, 500);
        setLayout(new FlowLayout());

        Button start = new Button("Start");
        Button stop = new Button("Stop");
        Button cont = new Button("Continue");
        Button reset = new Button("Reset");
        start.addActionListener(e -> startAnimation());
        stop.addActionListener(e -> stopAnimation());
        cont.addActionListener(e -> contAnimation());
        reset.addActionListener(e -> resetAnimation());
        add(start);
        add(stop);
        add(cont);
        add(reset);
        setVisible(true);

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                System.exit(0);
            }
        });

    }

    private void startAnimation() {
        isRunning = true;
        Thread animationThread = new Thread(() -> {
            while (isRunning) {
                update();
                repaint();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        animationThread.start();
    }

    private void stopAnimation() {
    }

    private void contAnimation() {
    }

    private void resetAnimation() {
    }

    private void update() {
        x += xSpeed;
        y += ySpeed;

        if (y > getHeight() - BALL_SIZE) {
            y = getHeight() - BALL_SIZE;
            ySpeed = -ySpeed - (ySpeed * (2 / 3));

        }

        if (x > getWidth() - BALL_SIZE) {
            x = getWidth() - BALL_SIZE;
        }
    }

    public void paint(Graphics Ball) {
        Ball.setColor(Color.ORANGE);
        Ball.fillOval(x, y, BALL_SIZE, BALL_SIZE);
    }

}
0

There are 0 best solutions below