%============================================================
%===== The Bouncing Ball With Stretch & Squash Function =====
%============================================================

clear
clc

Amplitude = 90;
StretchSquashAmplitude = 2;
Frequency = 0.5; %Oscillations Per Second
StretchSquashFrequency = 1;
Decay = 0.5; %Decay = 0 For No Decay
Phase = 0;
Duration = 10;
SamplingRate = 40;
AngularFrequency = 2*pi*Frequency;
StretchSquashAngularFrequency = 2*pi*StretchSquashFrequency;
Time = 0:1/SamplingRate:Duration;
PeriodCounter = 0;
ApplyStretchSquash = 1/(Frequency*4);

X = (1:length(Time));
for i=2:length(Time)
display(i);
         
    BouncingBallMovement(i) = abs(cos(AngularFrequency*Time(i) + Phase));
    BouncingBall = Amplitude*BouncingBallMovement./exp(Decay*Time(i));
    
    if (Time(i) > ApplyStretchSquash)
        StretchLevel(i) = StretchSquashAmplitude*sin(StretchSquashAngularFrequency*Time(i))./exp(Decay*Time(i));
        SquashLevel(i) = (1/X(i))*(StretchSquashAmplitude*StretchSquashAmplitude);
    else
        StretchLevel(i) = 0;
        SquashLevel(i) = 0;
    end
    
    if (rem(i,2) == 0)
        PeriodCounter = PeriodCounter + 1;      
    end
     
    figure(1);
    axis([-40 40 -20 100]);
    title('The Bouncing Ball With Stretch & Squash');
    xlabel('Time (Sec)');
    ylabel('Amplitude');
    grid on

    circle = rsmak('circle');
    BallShape = fncmb((circle),[2+(StretchLevel(i)+SquashLevel(i)) 0;0 2+(StretchLevel(i)-SquashLevel(i))]);
    Radious = 1/sqrt(2);
    Ball = fncmb(fncmb(BallShape,[-Radious Radious;Radious Radious]),[Time(i);BouncingBall(i)]);
    hold on
    
    if (PeriodCounter == 1)        
        fnplt(Ball,'r');
        PeriodCounter = 0;
    else
        fnplt(Ball);
    end
    
    hold off
end