- /
-
Falling triangles in colour
on 7 Nov 2023
- 8
- 96
- 1
- 2
- 462
drawframe(1);
Write your drawframe function below
function drawframe(f)
persistent h th s cnt
if f==1
rng default
set(gcf,"Color","k")
axes(Position=[0 0 1 1])
n=35;
cnt=rand(2,n); % center of initial triangles
xlim([0,1])
ylim(xlim)
hold on
axis off
th=2*pi*rand(4,n);
s=(rand(size(th))<.5)*2-1; % triangles are 3 coordinates along a circle
h=patch(nan,nan,"w",Clipping="off"); % triangle patches
colors = rand(n,3); % Initialize a 3-by-n matrix for RGB colors
h.FaceVertexCData=colors;
h.FaceColor='flat';
end
f=0.05;
th=mod(th+0.3*s,2*pi); % Shift the vertices
th(4,:)=th(1,:); % make sure the first and last match
cnt(2,:) = cnt(2,:)-1.1/48; % drop the location of the triangles
x=cnt(1,:)+f*cos(th); % update x coordinates
y=cnt(2,:)+f*sin(th); % update y coordinates
set(h,"XData",x,"YData",y) % update patch data
offAx=all(y<0,1); % which triangles have fallen off the axes?
cnt(2,offAx)=mod(cnt(2,offAx),1)+2*f; % Put off-axes triangles back on top
end