- /
- 
        Bouncy Ball
        on 26 Oct 2024
        
        
 
    - 25
- 161
- 0
- 0
- 1302
 Cite your audio source here (if applicable): 
drawframe(1);
 Write your drawframe function below
function drawframe(f)
    persistent hAx nBalls ballPatches ballX ballY ballR bps
    % setup
    if f==1
        % store axes handle
        hAx = gca();
        % set axes/figure properties
        set(hAx,...
            'Visible','off',...
            'Units','Normalized',...
            'InnerPosition',[0 0 1 1],...
            'XLim',[-1 1],...
            'YLim',[0 2],...
            'NextPlot','Add');
        set(gcf,'Color',[0 0 0]);
        % number of balls total
        nBalls = 100;
        % bounces/s
        bps = 0.5;
        % radii of the balls
        ballR = [0.1,linspace(0.05,0,nBalls-1)];
        % ball position coordinates
        ballX = linspace(0,1.5,nBalls)'; % always the same
        ballY = zeros(nBalls,1); % changes each frame
        % graphics placeholders for the ball patches
        ballPatches = gobjects(nBalls,1);
        % colors of each ball
        ballColors = flipud(hot(nBalls));
        % create a patch object for each ball
        for i = 1:nBalls
            ballPatches(i) = patch(hAx,...
                'XData',[],...
                'YData',[],...
                'FaceAlpha',1,...
                'FaceColor',ballColors(i,:),...
                'EdgeAlpha',0);
        end
        % change some properties on the main ball patch
        set(ballPatches(1),...
            'EdgeAlpha',1,...
            'LineWidth',1,...
            'EdgeColor',[0 0 0]);
        % invert the stacking order
        hAx.Children = flipud(hAx.Children);
    end
    % y position for each ball
    ballY = abs(sin((((f-1)/96)*2*pi*(bps)-(0:nBalls-1).'/nBalls )*2));
    for i = 1:nBalls
        % get patch data
        if ballY(i) < ballR(i) % ball is compressing
            % get ellipse patch data
            newY = max(ballY(i),0.5*ballR(i));
            a = min(2*ballR(i)-ballY(i),1.5*ballR(i));
            b = newY;
            [XData,YData] = getEllipseCoordinates(ballX(i),newY,a,b);
        else % ball is in the air
            % get circle patch data
            [XData,YData] = getCircleCoordinates(ballX(i),ballY(i),ballR(i));
        end
        % update patch data
        set(ballPatches(i),...
            'XData',XData,...
            'YData',YData);
    end
    drawnow;
    function [cX,cY] = getCircleCoordinates(centerX,centerY,r)
        theta = (0:1:359)';
        cX = r*cosd(theta)+centerX;
        cY = r*sind(theta)+centerY;
    end
    function [cX,cY] = getEllipseCoordinates(centerX,centerY,a,b)
        theta = (0:1:359)';
        cX = a*cosd(theta)+centerX;
        cY = b*sind(theta)+centerY;
    end
end
Movie
Audio
This submission does not have audio.


 

