I wrote a function caterpillar
that takes arrays of x and y values and plots several circles following the line described by the coordinates. Next I need to write a function that will make the caterpillar
move inside a rectangle for an input number of iterations. My problem is that I cannot figure out a simple way to calculate the path it would take. When caterpillar reaches the boundaries of the rectangle it should reflect and go in another direction. I am trying to create the whole trajectory beforehand, put it into an array and then feed to caterpillar
. I was thinking of somehow using minus signs as to represent reflections but I don’t know how to update my x
and y
coordinates appropriately.
This is my current code for the function:
function caterpool(pos,spee,bl,tr,n)
# pos - initial position
# spee - speed vector
# bl - bottom left corner of rectangle
# tr - top right corner of rectangle
# n - number of iterations
line = polyfit([pos(1), spee(1)], [pos(2), spee(2)], 1);
x = linspace(pos(1), tr(1));
f = @(x)line(1).*x+line(2);
y = f(x);
a = line(1);
b = line(2);
xbl = bl(1);
xtr = tr(1);
ybl = bl(2);
ytr = tr(2);
plot(x,y)
hold on
rectangle('Position', [bl(1) bl(2) tr(1)-bl(1) tr(2)-bl(2)]);
axis equal
f_x = zeros(1, n);
f_y = zeros(1, n);
x0 = pos(1); y0 = pos(2);
for i=1:n
f_x(i) = x0;
f_y(i) = y0;
x0 += spee(1);
y0 += f(spee(1));
endfor
caterpillar(f_x, f_y, 3)
# points of intersection with the rectangle boundaries
disp([ybl-line(2), ybl]);
disp([ytr-line(2), ytr]);
disp([xbl, f(xbl)]);
disp([xtr, f(xtr)]);
This is how caterpillar
looks like:
function caterpillar(tx,ty,n)
if n <= length(tx)
p = polyfit(tx, ty, length(tx) - 1);
x1 = linspace(min(tx), max(tx), length(tx));
y1 = polyval(p, x1);
plot(x1, y1)
hold on;
xc=0; yc=0; r=0.5;
th = 0:pi/50:2*pi;
x = r * cos(th) + xc;
y = r * sin(th) + yc;
h = zeros(n, 1);
for i=1:n
h(i) = plot(x,y);
endfor
for k=1:length(x1)
for i=1:n
if k>i-1
set(h(i), 'XData', x + x1(k-i+1));
set(h(i), 'YData', y + y1(k-i+1));
endif
endfor
pause(0.1);
endfor
endif
Could anybody please help or give a hint? Thanks in advance.