%% Nested Hierarchy of Transforms
% This example shows how to create a nested hierarchy of
% transforms
%% Set Up  Axes

% Copyright 2015 The MathWorks, Inc.

fig = figure('Visible','off');
axes('Projection','perspective')
view(3)
axis equal
grid on
%% Create Hierarchy of Hgtransform Objects
t = hgtransform;
t(2) = hgtransform('parent',t(1));
t(3) = hgtransform('parent',t(2));
t(4) = hgtransform('parent',t(3));
t(5) = hgtransform('parent',t(4));
t(6) = hgtransform('parent',t(5));
%% Define Patch and Text Data
% Parent patch/text pairs to the respective hgtransform. Use
% the same data to define the size square sides of a cube. 
X = [0 0 1 1];
Y = [0 1 1 0];
Z = [0 0 0 0];

Xtext = 0.5;
Ytext = 0.5;
Ztext = 0.15;
%% Create Patch and Text Objects
% Save handles in two arrays p and txt
p(1) = patch('FaceColor','red','Parent',t(1));
txt = text('String','Bottom',...
   'Parent',t(1));

p(2) = patch('FaceColor','green','Parent',t(2));
txt(2) = text('String','Right',...
   'Visible','off',...
   'Parent',t(2));

p(3) = patch('FaceColor','blue','Parent',t(3));
txt(3) = text('String','Back',...
   'Color','white',...
   'Visible','off',...
   'Parent',t(3));

p(4) = patch('FaceColor','yellow','Parent',t(4));
txt(4) = text('String','Top',...
   'Visible','off',...
   'Parent',t(4));

p(5) = patch('FaceColor','cyan','Parent',t(5));
txt(5) = text('String','Left',...
   'Visible','off',...
   'Parent',t(5));

p(6) = patch('FaceColor','magenta','Parent',t(6));
txt(6) = text('String','Front',...
   'Visible','off',...
   'Parent',t(6));
%% Assign Patch and Text Data
set(p,'XData',X,'YData',Y,'ZData',Z)
set(txt,'Position',[Xtext Ytext Ztext],...
    'HorizontalAlignment','center',...
    'VerticalAlignment','middle')
 %% Translate Cube Sides
 % Spread sides onto the same plane in preparation to folding all 
 % sides into a cube. As you apply each transform, the children of 
 % that hgtransform are also translated. Therefore, each translation 
 % requires moving the square by only one unit in either the
 % x or y direction. The bottom of the cube (red-colored
 % side) can remain in its original position and is not
 % translated.
 Tx = makehgtform('translate',[1,0,0]);
 Ty = makehgtform('translate',[0,1,0]);
 for k = 2:6
   t(k).Matrix = Tx;
   txt(k).Visible = 'on';
   pause(1)
 end
fig.Visible = 'on';
 %% Assign Transforms
 fold = pi/2;
 Ry = makehgtform('yrotate',-fold);
 RyTx = Tx*Ry;
 Rx = makehgtform('xrotate',fold);
 RxTy = Ty*Rx;
 %% Apply Transforms
 % Apply each transform in the reverse order to fold the
 % sides into a cube. The pause function slows the rendering
 % and causes the display to update.
 t(6).Matrix = RyTx;
 pause(1)
 t(5).Matrix = RxTy;
 pause(1)
 t(4).Matrix = RyTx;
 pause(1)
 t(3).Matrix = RxTy;
 pause(1)
 t(2).Matrix = RyTx;
 pause(1)
 
 
 
 
 
 
 
 
 