make filled shapes move in MATLAB

断了今生、忘了曾经 提交于 2019-12-03 23:07:03

问题


I have the following statement for drawing filled rectangler and cirle shapes in matlab. What I have to add for those statement only to make shapes between start point and target point for each without collision.

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:


Example with a rectangle. The trick is to gradually modify the object properties, in this case its '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


Example with a rectangle and a circle. The approach is similar: create both objects and update their 'Vertices' property within the 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



来源:https://stackoverflow.com/questions/24181618/make-filled-shapes-move-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!