% Unit 2 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%============
% CANNONBALL
%============
clear all, clc, close all


% constants
gEarth     = -9.79757; % m/s^2
gMoon      = -1.622;   % m/s^2
gy         = gEarth;
gx         = 0.0;

% input values
N     = 100;     % points
x0    = 3.;      % m
y0    = 2.;      % m
v0    = 10.;     % m/s (NOTE: total velocity!)
alpha = 23.;     % degrees

% inital velocity transformed to [vxy, vy0]
vx0   = v0*cos(alpha * 2*pi/360.);
vy0   = v0*sin(alpha * 2*pi/360.);

% time arrays (Note: Tend is the time until return to y=y0)
Tend  = -(2*vy0)/gy
t     = linspace(0,Tend,N);

% analytical cannonball solution
x  = x0  + vx0.*t + 0.5.*gx.*t.^2;
y  = y0  + vy0.*t + 0.5.*gy.*t.^2;

%vx = vx0 .* ones(1,N); % making explicit use of the knowledge that gx=0
vx = vx0 +  gx.*t;
vy = vy0 +  gy.*t;


% plot cannonball solution
plot(x, y), xlabel('x'), ylabel('y')
hold on
plot(x,y,'o')

% find maximum height, using the idea from Unit2.pdf

% difference between two neighbouring y-points
dy = diff(y);
% find all the positions with dy<0
i = find(dy<0);
% the first entry in vector i() is the desired position in vector y()
ymax = y(i(1));
xmax = x(i(1));
tmax = t(i(1));
ymax, xmax, tmax

% we could also achieve this by simply using MATLAB's function max()
[ymax,imax] = max(y);
xmax = x(imax);
tmax = t(imax);
ymax, xmax, tmax


hold on
plot([xmax xmax],[min(y) max(y)],'r')
plot([min(x) xmax],[ymax ymax],'r')
hold off



