// Yazzy Latif // 07/10/2020 // CSE142 // TA: Grace Hopper // To Days lecture example // This program animates a ball bouncing around // at a particular angle and with a particular velocity // provided by the user. /* DEVELOPMENT NOTES: ((Note: this is not something you should include in your own programs; this is included here to aid in your understanding and to provide additional context for the program.)) In this version of the Ball program we added a console Scanner to prompt and read for velocity, angle, and seconds for the animation. We also added if statements to make the ball bounce around in the DrawingPanel. */ import java.awt.*; import java.util.*; public class Ball2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); // below shows 3 examples of the prompt and read pattern // to get user input System.out.print("velocity? "); double velocity = console.nextDouble(); // pixels per second System.out.print("angle? "); double angle = console.nextDouble(); System.out.print("seconds? "); int seconds = console.nextInt(); double xVelocity = velocity * Math.cos(Math.toRadians(angle)); // yVelocity is negative b/c on the DrawingPanel // as we move down in the DrawingPanel the y-coordinate // gets larger. If we want it to move towards the top right // we need to flip the sign of the velocity so y // gets smaller double yVelocity = -velocity * Math.sin(Math.toRadians(angle)); DrawingPanel panel = new DrawingPanel(600, 600); panel.setBackground(Color.CYAN); Graphics g = panel.getGraphics(); // draw initial ball // we want the center of the ball to be at 300, 300 we need // to subtract 5 from x and y since fillOval is relative to // the top right corner of the box that encapsulate the oval g.fillOval(295, 295, 10, 10); panel.sleep(1000); double x = 300.0; double y = 300.0; for (int i = 1; i <= 10 * seconds; i++) { // Draw a white ball over previous black ball location // to create a trajectory line g.setColor(Color.WHITE); g.fillOval((int) x - 5, (int) y - 5, 10, 10); // draw next frame x = x + xVelocity / 10.0; y = y + yVelocity / 10.0; // these if statements allows the ball to // bounce around if (x <= 5 || x >= 595) { xVelocity = -xVelocity; } if (y <= 5 || y >= 595) { yVelocity = -yVelocity; } // x = 715.325 g.setColor(Color.BLACK); g.fillOval((int) x - 5, (int) y - 5, 10, 10); panel.sleep(100); } } }