Home > OS >  How do I make the MATLAB code animate a bouncing ball
How do I make the MATLAB code animate a bouncing ball

Time:02-26

    close all;
    clear all;
    clc;
% height and period of time per data change
timeStep = 0.0005;
height = zeros(4e4,1);
% acceleration
g = 9.81;
% COR and initial height
COR = 0.8;
height(1)=15;
% initial speed
v = 0;


for i=2:length(height)
    v = v - g*timeStep;
    %new height
    height(i)=max(0,height(i-1) v*timeStep);
    % stop ball from going below ground      
    if height(i)<=0
        % change velocity direction
        v = -COR*v;                      
    end

end  
% plot height on y and time on x axis
time = (1:4e4)*timeStep;
plot(time,height);
% turn into animation
%z = plot(time,height,'o','markerfacecolor','r','markersize',11);
i = 0;
while 1
    %set(z,'XData',time,'YData',height);
    %drawnow
    time2 = time(i);
    height2 = height(i);
    plot(time2,height2,'o','markerfacecolor','r','markersize',11);
    axis([0 15 0 15]);
    i = i   1;
    pause(0.1);
end   
grid on; 
box on;

CodePudding user response:

I spotted a small error. Your index i should start at 1 instead of 0. Appart from that, all you need is update the graph with drawnow. The documentation can be found here.

As you provided this method within your comments I might suggest having a look at pause(0.1) as this would mean your animation needs over 16 minutes to complete. There might have been updates on your graph without you noticing because of the small timestep.

Using the code you commented out this would be one possible solution.

% turn into animation
z= plot(time(1),height(1),'o','markerfacecolor','r','markersize',11);
axis([0 15 0 15]);
grid on;
box on;
for i = 2:length(height)
    set(z,'XData',time(i),'YData',height(i));
    drawnow limitrate
end
  • Related