- /
-
Floating Balls
on 27 Oct 2024
- 22
- 118
- 0
- 0
- 1394
Cite your audio source here (if applicable):
drawframe(1);
Write your drawframe function below
function drawframe(f)
persistent Xw Yw Zw Hw Xb Yb Zb Ub Vb D Nb balls xballs yballs zballs water balldropping twave
if(f == 1)
%% Create a figure and set position and background color
fig = figure; fig.Position = [10 50 900 550]; fig.Color = 'w';
%% Generate the meshgrid that will be use to represent water wave
[Xw, Yw] = meshgrid(-20:0.1:20); Hw = 1; Zw = Hw + zeros(size(Xw));
water = surf(Xw,Yw,Zw, EdgeColor = 'w', EdgeAlpha = 0.4,FaceColor = 'none');
hold on; daspect([1,1,1]);
%% Set the bound, relative dimensions and lighting.
axis([-20,20,-20,20,0,15]); axis off; camlight; lighting gouraud;
%% Generate a ball using the sphere and extract default colors from matlab
[Xb,Yb,Zb] = sphere(50); clrs = get(gca,'colororder');
%% Set number of balls and generate random positions
Nb = 3; r = rand(3,Nb); xballs = -19+r(1,:)*38; yballs = -19+r(2,:)*38;
zballs = 2+r(3,:)*12; balls = {}; D = {};
for n = 1:Nb
ball = surf(Xb + xballs(n), Yb + yballs(n), Zb + Hw + zballs(n));
ball.FaceColor = clrs(n,:); ball.EdgeAlpha = 0.1; balls = [balls, ball];
d = sqrt((Xw - xballs(n)).^2 + (Yw - yballs(n)).^2); D = [D,d];
end
%% initial and final velocities for each ball
Vb = zeros(1,Nb); Ub = zeros(1,Nb);
%% Set logic to indicate ball is dropping, and set timer for wave
balldropping = zballs > Hw; twave = zeros(1,Nb);
else
%% Set gravity
g = 5;
%% Define wave characteristics and set wave equation
wavevel = 10; decayrate = 0.1; amplitude = 0.25; wavenum = 4;
wave_eq = @(x,t) amplitude*exp(-decayrate*(t+x)).*sin((wavenum*x-wavevel*t));
%% Begin simulation
dt = 0.05; % Get change in time
dv = -g*dt; % Get change in velocity
water.ZData = Zw; % Set water to initial state
for n = 1:Nb
if(balldropping(n)) % If ball is droping
% Update velocity and ball position
Vb(n) = Ub(n) + dv; zballs(n) = zballs(n) + 0.5*(Vb(n)+Ub(n))*dt;
% Update graphic handle of the ball
balls(n).ZData = balls(n).ZData + 0.5*(Vb(n) + Ub(n))*dt;
else % Ball is already on water
% Accumuate wave time and extract radial positions from the ball
twave(n) = twave(n) + dt; d = D{n};
% Accumulate wave positions to reflect interference
water.ZData = water.ZData + wave_eq(d, twave(n)).*(d <= wavevel*twave(n));
% Update ball position with wave_eq(0, t) to make it float
balls(n).ZData = Zb + Hw + wave_eq(0, twave(n));
end
end
%Update ball is dropping logic and initial velocity and render objects
balldropping = zballs > Hw; Ub = Vb;
drawnow;
end
end
Movie
Audio
This submission does not have audio.