// CSE 142 Lecture 7 // Math, returns import java.awt.*; // For Graphics and Color // This program computes and draws the trajectory of a projectile. public class Projectile { public static final double GRAVITY = -9.81; public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(420, 250); Graphics g = panel.getGraphics(); // v0, angle, steps buildTable(g, 60, 50, 10); g.setColor(Color.RED); buildTable(g, 50, 80, 50); } // Calculates the position of an object based on its initial speed, the time // elapsed, and the force of acceleration. // x = v0 * t + 1/2 * a * t^2 public static double position(double velocity, double time, double acceleration) { return velocity * time + 0.5 * acceleration * Math.pow(time, 2); } // Prints a table of the step, x/y position, and time elapsed for each // time step. Also draws the ball's trajectory. public static void buildTable(Graphics g, double velocity, double angle, int steps) { // Convert angle to radians to find x and y component of velocity. double angleRadians = Math.toRadians(angle); double vY = velocity * Math.sin(angleRadians); double vX = velocity * Math.cos(angleRadians); double totalTime = -2 * vY / GRAVITY; // The total time the ball spends in the air double dT = totalTime / steps; // The time that each step takes System.out.printf("%4s%8s%8s%8s\n", "step", "x", "y", "time"); for (int i = 0; i <= steps; i++) { double elapsed = dT * i; double x = position(vX, elapsed, 0); double y = position(vY, elapsed, GRAVITY); System.out.printf("%4d%8.2f%8.2f%8.2f\n", i, x, y, elapsed); g.fillOval((int)x, 250 - (int)y, 5, 5); } } }