// Helene Martin, CSE 142 // Animates two falling balls affected by gravity. import java.awt.*; import java.util.*; public class BallSimulation { public static final int PANEL_SIZE = 400; public static final int BALL_SIZE = 40; public static final double GRAVITY_ACC = 9.81; // m / sec^2 public static final double TIME_STEP = 0.1; // secs public static void main(String[] args) { Scanner s = new Scanner(System.in); // Note: the following 5 line are redundant. // We can only return one thing from a method and they get 3 values. // For now, we can't reduce this redundancy. System.out.print("Ball 1 starting x y: "); int ball1x = s.nextInt(); int ball1y = s.nextInt(); System.out.print("Ball 1 starting velocity: "); double ball1V0 = s.nextDouble(); System.out.print("Ball 2 starting x y: "); int ball2x = s.nextInt(); int ball2y = s.nextInt(); System.out.print("Ball 2 starting velocity: "); double ball2V0 = s.nextDouble(); DrawingPanel panel = new DrawingPanel(PANEL_SIZE, PANEL_SIZE); Graphics g = panel.getGraphics(); for(double t = 1; t <= 10; t += TIME_STEP) { double ball1Disp = displacement(ball1V0, GRAVITY_ACC, t); g.setColor(Color.RED); g.fillOval(ball1x, (int)(ball1y + ball1Disp), BALL_SIZE, BALL_SIZE); double ball2Disp = displacement(ball2V0, GRAVITY_ACC, t); g.setColor(Color.BLUE); g.fillOval(ball2x, (int)(ball2y + ball2Disp), BALL_SIZE, BALL_SIZE); 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 a, double t) { return v0 * t + (a / 2) * Math.pow(t, 2); } }