使填充的形状在MATLAB中移动

时间:2014-06-12 10:01:14

标签: matlab matlab-figure

我有以下声明在matlab中绘制填充的rectangler和cirle形状。 我必须为这些语句添加的内容仅为每个没有碰撞的起点和目标点之间的形状。

fill([9.5 9.5 11.5 11.5 ],[12.6 14.6 14.6 12.6],'r');  %rectangler shape
hold on
r=1; 
color=[1 0 0]; 
t=linspace(0,2*pi);
fill(15+r*cos(t),8+r*sin(t),color); %circle shape
grid on

1 个答案:

答案 0 :(得分:4)

带矩形的示例。诀窍是逐步修改对象属性,在本例中为'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


带有矩形和圆形的示例。方法类似:创建两个对象并在'Vertices'循环内更新其for属性。

%// 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