【问题标题】:make filled shapes move in MATLAB使填充的形状在 MATLAB 中移动
【发布时间】:2014-06-12 22:18:04
【问题描述】:

我有以下语句用于在 matlab 中绘制填充的矩形和圆形。 我必须为这些语句添加的内容只是为了在每个没有碰撞的情况下在起点和目标点之间制作形状。

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

【问题讨论】:

  • 您能否定义并举例说明您的起点和目标?
  • 每个形状的中心点是起点,例如圆形的起点是S=[15 8];我们可以假设目标点是T=[1 1];
  • 所以你有矩形和圆形的对象。您想移动它们并确保它们永远不会重叠吗?那是对的吗?如果它们重叠会发生什么?
  • 是的,这是非常正确的
  • 如果它们相互碰撞,则应改变运动方向

标签: matlab matlab-figure


【解决方案1】:

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


以矩形和圆形为例。方法类似:创建两个对象并在for 循环中更新它们的'Vertices' 属性。

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

【讨论】:

  • 嗯...有时我想知道为什么我看起来这么慢... :-)。我刚要发帖。你得到了我的 +1
  • @user3481947 从我的例子中应该很明显。方法是一样的
  • 我运行了两个对象。但是它们不会同时工作。当他们第一个完成时,第二个开始。
  • 将两个更新放在for 循环中:为第二个对象添加类似的行x2 = ...y2 = ...set(h2, ...)
  • @user3481947 我已经包含了两个对象的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 2018-06-15
  • 2017-03-12
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多