How do you make an animation of many objects?

1 view (last 30 days)
I want to know how to create an array of objects that I can animate on the screen. I don't see any documentation about making arrays of objects. I have included a simple script below that animates one object.
%Set axes
figure
axis([-10,10,-10,10]);
axis('square');
grid minor
%Define constants
m=0.39;
%Initialize time, position, velocity, momentum
r=[0,0,0];
v=[10,20,0];
p=m*v;
t=0;
tmax=10;
%Set time step
dt=0.01;
%Draw the ball
hold on
ball=plot(r(1,1),r(1,2),'o','markersize',8,'MarkerFaceColor', 'red');
xlabel('X Position (m)');ylabel('Y Position (m)');
hold off;
%An iterative loop
while (t<tmax)
r=r+(p/m)*dt; %Position update
t=t+dt; %Time update
if ((r(1,1) <=-10) || (r(1,1)>= 10))
p(1,1)=-p(1,1);
end
if ((r(1,2) <=-10) || (r(1,2)>= 10))
p(1,2)=-p(1,2);
end
ball.XData=r(1,1);
ball.YData=r(1,2);
drawnow;
end

Answers (1)

Walter Roberson
Walter Roberson on 13 Oct 2015
If you want to use the same marker for all of the balls then the easiest approach is to use scatter(), and update the XData and YData properties with the vector of positions.
If you want to use different markers then you need one scatter() per marker shape.
Alternately you can use an array:
ball(K) = plot(r(K,1),r(K,2),'o','markersize',8,'MarkerFaceColor', 'red');
...
ball(K).XData = r(K,1);
ball(K).YData = r(K,2);

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!