Flipping ball Ball.m

Create a figure with white background.

h=figure;
set(h,'Color','w');
% Define the working area.
xmin=0;
xmax=100;
ymin=0;
ymax=100;
% Define the ball.
R=5;
% Define the initial position of the ball.
x=R+rand(1)*(xmax-2*R);
y=R+rand(1)*(ymax-2*R);
% Define the initial step.
dx=rand(1)*2;
dy=rand(1)*2;
% Define time limit.
tmax=10; % seconds
% Ellapsed time.
t=0;
% Start time measurement.
tic
% Start loop.
while t<tmax
    % Calculate new position.
    x=x+dx;
    y=y+dy;
    % Verify and correct position and step direction.
    if x<xmin+R || x>xmax-R
        % Change direction.
        dx=-dx;
        % Recalculate position.
        x=x+dx;
    end
    if y<ymin+R || y>ymax-R
        % Change direction.
        dy=-dy;
        % Recalculate position.
        y=y+dy;
    end
    % Plot ball.
    Circle(x,y,R);
    axis([ xmin xmax ymin ymax])
    % Display ellapsed time.
    title(sprintf('Ellapsed time: %6.2f [s]',t));
    pause(0.01)
    % Get ellapsed time.
    t=toc;
end