// Helene Martin, CSE 142 // Simulates two balls with initial y velocity falling due to gravity. // goal: show complex drawing panel program and demonstrate // user input with Scanner import java.awt.*; import java.util.*; public class BallSimulation { public static final double ACC_GRAVITY = 9.81; // pixels/s^2 public static final int BALL_DIAMETER = 70; public static final double TIME_STEP = .1; // s public static void main(String[] args) { Scanner console = new Scanner(System.in); // Note: the two blocks of code that follow are redundant. // They each capture 3 pieces of information, though, and // we can only return 1 thing from a method! So for now we // live with it. System.out.print("Give me the x and y coordinate of ball 1: "); int ball1x = console.nextInt(); int ball1y = console.nextInt(); System.out.print("Give me an initial velocity for ball 1: "); double ball1V0 = console.nextDouble(); System.out.print("Give me the x and y coordinate of ball 2: "); int ball2x = console.nextInt(); int ball2y = console.nextInt(); System.out.print("Give me an initial velocity for ball 2: "); double ball2V0 = console.nextDouble(); // Create the DrawingPanel later so it doesn't pop up DrawingPanel panel = new DrawingPanel(400, 400); Graphics g = panel.getGraphics(); // calculate position and draw balls at each time step for (double t = 0; t < 10; t += TIME_STEP) { g.setColor(Color.RED); double disp1 = displacement(ball1V0, t, ACC_GRAVITY); g.fillOval(ball1x, ball1y + (int)disp1, BALL_DIAMETER, BALL_DIAMETER); g.setColor(Color.BLUE); double disp2 = displacement(ball2V0, t, ACC_GRAVITY); g.fillOval(ball2x, ball2y + (int)disp2, BALL_DIAMETER, BALL_DIAMETER); panel.sleep((int)(1000 * TIME_STEP)); panel.clear(); } } // Calculates the displacement of an objects starting at velocity v0 // after t seconds have passed, given an acceleration of a. public static double displacement(double v0, double t, double a) { return v0 * t + (a * Math.pow(t, 2)) / 2; } }