bouncing ball animation in matlab

Here is a simple bouncing ball animation in MATLAB:

main.m
clc;
clear all;
close all;

% Initialization
x = 0; % x-position of the ball
y = 0; % y-position of the ball
vx = 0.2; % x-velocity of the ball
vy = 0.5; % y-velocity of the ball
g = 0.01; % acceleration due to gravity
dt = 0.01; % time step

% Set up figure
figure;
axes('XLim',[-1 1],'YLim',[-1 1],'Position',[0.1 0.1 0.8 0.8]);
h = rectangle('Position',[x y 0.1 0.1],'Curvature',[1 1],'FaceColor','r');

% Loop for animation
while true
    % Update position and velocity
    x = x + vx*dt;
    y = y + vy*dt;
    vy = vy - g*dt;

    % Bounce off the walls
    if x < -1 || x > 1
        vx = -vx;
    end
    if y < -1
        vy = -vy;
    end

    % Update ball position
    set(h,'Position',[x y 0.1 0.1]);

    % Pause for a short time
    pause(dt);
end
763 chars
39 lines

This code creates a window with a bouncing ball that moves in a parabolic trajectory due to the effect of gravity. The velocity and acceleration can be adjusted to create a different trajectory. The position and velocity of the ball are updated every time step, and the ball bounces off the walls if it hits them. Finally, the ball position is updated on the display using the set() function, and the animation is paused for a short time using the pause() function.

related categories

gistlibby LogSnag