package physics;

import stdlib.StdDraw;

/*************************************************************************
 *  Compilation:  javac BallisticMotion.java
 *  Execution:    java BallisticMotion v theta
 *  Dependencies: StdDraw.java
 *
 *  Simluate the motion of a ball fired with velocity v at theta degrees
 *  with coefficient of drag C. Uses Euler-Cramer method to numerically
 *  solve differential equation.
 *  
 *  % java BallisticMotion 180.0 60.0
 *
 *  % java BallisticMotion 20.0 45.0
 *
 *************************************************************************/

public class BallisticMotion {

   public static void main(String[] args) {
      double G = 9.8;     // gravitational constant m/s^2
      double C = 0.002;   // drag force coefficient

//      double v     = Double.parseDouble(args[0]);                    // velocity
//      double theta = Math.toRadians(Double.parseDouble(args[1]));    // angle in radians
      double v = 40.0;
      double theta = 60.0*Math.PI/180;

      double x = 0.0, y = 0.0;           // position
      double vx = v * Math.cos(theta);   // velocity in x direction
      double vy = v * Math.sin(theta);   // velocity in y direction

      double ax = 0.0, ay = 0.0;         // acceleration
//      double t  = 0.0;                   // time
      double dt = 0.01;                  // time quantum

      double maxR = v*v / G;             // maximum distance without drag force     
  	  StdDraw sd = new StdDraw();   
      sd.setXscale(0, maxR);
      sd.setYscale(0, maxR);        // set the same as for X-scale

      // loop until ball hits ground
      while (y >= 0.0) {
         v = Math.sqrt(vx*vx + vy*vy);
         ax = -C * v * vx;
         ay = -G - C * v * vy;
         vx += ax * dt;
         vy += ay * dt;
         x  += vx * dt;
         y  += vy * dt;
         StdDraw.filledCircle(x, y, 0.25);
         sd.show(5);
      }
      StdDraw.show();
   }
   
}
