Search code examples
matlabsimulationpoint

moving a train of points (cars)


We are trying to simulate moving cars using different coloured and sized points (car type 1 : red size 20, car type 2 : green size 40 and so on), the problem is if there was two cars of the same type they overlap where they should follow each other, this is the used code:

x = linspace(0,30,1000);
axis([0,20,-0.4,1.5]);
ax = gca;
h = hgtransform('Parent',ax);
type1=plot(-1,0.4,'s','Parent',h,'MarkerFaceColor','red','MarkerSize',20);
type2=plot(-1,0.4,'s','Parent',h,'MarkerFaceColor','green','MarkerSize',40);
car=[1 2 2 1 1];
for k = 1:10:700
    for i = 1:length(car)
       if(car(i)==1)
           set(type1,'XData',x(k),'YData',0.4);
           pause(0.1);
       elseif(car(i)==2)
           set(type2,'XData',x(k)-3,'YData',0.4);
           pause(0.1);
       end
    end
end

How to keep sequence that every (x=3) a new car start moving without deleting or over lapping the cars in front of it.

Thanks inadvance


Solution

  • You might want below code.

    x = linspace(0,30,1000);
    axis([0,20,-0.4,1.5]);
    ax = gca;
    car=[1 2 2 1 1];
    h = hgtransform('Parent',ax);
    Ncar=length(car);
    
    for n=1:Ncar %generate 5 cars having one type among type1 and type2
        if car(n)==1;
           types(n)=plot(-1,0.4,'s','Parent',h,'MarkerFaceColor','red','MarkerSize',20);
        else
           types(n)=plot(-1,0.4,'s','Parent',h,'MarkerFaceColor','green','MarkerSize',40);
        end
    end
    
    for k = 1:10:700 %plotting the cars sequencially
        for i = 1:length(car)  
               set(types(i),'XData',x(k)-3*(i-1),'YData',0.4);
           pause(0.1);
        end
    end