how to put a function inside animation
1 view (last 30 days)
Show older comments
Meriem Boukhaima
on 7 Jan 2017
Commented: Walter Roberson
on 7 Jan 2017
Hi, I have to program a bouncing ball using a function I created before called drawball, now I can't implement this function inside my program, it only shows me a big ball, here are the scripts I used:
function drawdisc(x0,y0,r,c)
t=0:0.01:2*pi;
x=r*cos(t)+x0;
y=r*sin(t)+y0;
fill(x,y,c)
end
the bouncing ball script:
clc;
initpos=0; %Ball's initial vertical position
initvel=20; %Ball's initial vertical velocity
r_ball=1; %Ball's radius
gravity=10; %Gravity's acceleration
c_bounce=0.85; %Bouncing's coefficient of elasticity
dt=0.0125; %Animation timestep;
pos=r_ball; %Ball's current vertical position
vel=initvel;%Ball's current vertical velocity
axis([0 20 0 25])
while 1
pos=pos+(vel*dt); %Ball's current vertical position
vel=vel-(gravity*dt); %Ball's current vertical velocity
if pos<0
vel=-vel*c_bounce; %Balls' current vertical velocity
end
drawball(1,pos,1,'b')
pause(0.01)
end
your help is appreciated!!
0 Comments
Accepted Answer
Walter Roberson
on 7 Jan 2017
You define a function named "drawdisc" but you call upon "drawball" in your code.
You call upon drawball(1,pos,1,'b') in your code. It would make more sense to call upon drawball(1,pos,r_ball,'b')
If you the Image Processing Toolbox and a newer MATLAB you might want to consider using viscircles() instead of your own routine. You might also want to consider using scatter() with a marker size and with 'filled'. Or you might want to use plot() with 'o' as the marker and with a MarkerSize and MarkerFaceColor argument.
2 Comments
Walter Roberson
on 7 Jan 2017
You need to either "hold on" or set the axes xlim and ylim (which automatically sets xlimmode and ylimmode to manual). Make sure you do that after each time you draw the ball. (Better yet would be for your drawing routine to detect that the ball had already been drawn and to update its position instead of creating a new drawing, but even that requires that you had set xlim and ylim)
More Answers (0)
See Also
Categories
Find more on Animation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!