以矩形为例。诀窍是逐渐修改对象属性,在本例中是它的'Vertices'
origin_x = [9.5 9.5 11.5 11.5 ]; %// initial coordinates of vertices
origin_y = [12.6 14.6 14.6 12.6];
destination_x = origin_x + 3; %// final coordinates of vertices
destination_y = origin_y + 2;
n_steps = 100; %// number of "frames"
t_pause = .03; %// seconds between frames
h = fill(origin_x, origin_y, 'r'); %// create object at initial position
axis([8 16 10 18]) %// adjust as needed, to cover the desired area
axis equal %// same scale in both axes
axis manual %// prevent axes from auto-scaling
for t = linspace(0,1,n_steps)
x = (1-t)*origin_x + t*destination_x; %// update x
y = (1-t)*origin_y + t*destination_y; %// update y
set(h, 'Vertices', [x(:) y(:)]) %// change object's position
pause(t_pause) %// a pause is needed to make movement slower
drawnow %// probably not needed after pause. Just in case
end
![enter image description here](https://i.stack.imgur.com/oCwOP.gif)
以矩形和圆形为例。方法类似:创建两个对象并更新它们'Vertices'
内的财产for
loop.
%// Define rectangle values
origin_x1 = [9.5 9.5 11.5 11.5 ];
origin_y1 = [12.6 14.6 14.6 12.6];
destination_x1 = origin_x1 + 3;
destination_y1 = origin_y1 + 2;
%// Define circle values
r = 1;
v = linspace(0,2*pi);
origin_x2 = 15+r*cos(v);
origin_y2 = 10+r*sin(v);
destination_x2 = origin_x2 - 1;
destination_y2 = origin_y2 + 3;
%// Define movement speed
n_steps = 100;
t_pause = .03;
%// Create objects
h1 = fill(origin_x1, origin_y1, 'r');
hold on
h2 = fill(origin_x2, origin_y2, 'b');
axis([8 16 10 18])
axis equal
axis manual
%// Update properties
for t = linspace(0,1,n_steps)
x1 = (1-t)*origin_x1 + t*destination_x1;
y1 = (1-t)*origin_y1 + t*destination_y1;
set(h1, 'Vertices', [x1(:) y1(:)])
x2 = (1-t)*origin_x2 + t*destination_x2;
y2 = (1-t)*origin_y2 + t*destination_y2;
set(h2, 'Vertices', [x2(:) y2(:)])
pause(t_pause)
drawnow
end
![enter image description here](https://i.stack.imgur.com/KzmWe.gif)