Creating a 2D moving object
조회 수: 23 (최근 30일)
이전 댓글 표시
I would to create a 2D environment where an object (i.e. a basic shape) moves between defined positions.
Is it possible to set up this kind of system in MATLAB and how would I go about doing it?
댓글 수: 0
채택된 답변
Mike Garrity
2015년 9월 30일
Sure, here's a simple example.
First we create an object. I'm using patch because it's good at all sorts of 2D shapes, and I'm putting it into a hgtransform because that will make it easy to move around:
x = [-1 , 1/3, 1/3, 1, 1/3, 1/3,-1 ];
y = [-1/3,-1/3,-1/2, 0, 1/2, 1/3, 1/3];
g = hgtransform;
patch('XData',x,'YData',y,'FaceColor','yellow','Parent',g)
Now we set up the coordinate system we want to move around in. The axis equal means that the scale in the X & Y directions will be the same, rather than the arbitrary scaling you use for charts.
axis equal
xlim([-10 10])
ylim([-10 10])
And then we can easily move between two points like this. The basic idea is to do linear interpolation between the two points and give the result to the makehgtform function to get a transform matrix. The hgtransform object will use that to move the patch.
pt1 = [-3 -4 0];
pt2 = [5 2 0];
for t=linspace(0,1,100)
g.Matrix = makehgtform('translate',pt1 + t*(pt2-pt1));
drawnow
end
We can easily add in scaling and rotating too.
s1 = 1/2;
s2 = 2;
r1 = 0;
r2 = 2*pi/3;
for t=linspace(0,1,100)
g.Matrix = makehgtform('translate',pt1 + t*(pt2-pt1), ...
'scale',s1 + t*(s2-s1), ...
'zrotate',r1 + t*(r2-r1));
drawnow
end
Is that enough to get started?
댓글 수: 4
Atakan Botasun
2021년 6월 13일
Could implement a pause line, i.e.
pause(1)
Note that this example line will stop MATLAB execution completely for a second. Nothing will work for that one second. Make sure that it doesn't break things.
추가 답변 (1개)
Ikke dettenei
2018년 6월 18일
I was wondering. Is it possible to create a Electric vehicle simulation where a certain amount of EV`s are moving around and when they are low on battery, moving to the nearest charging station?
I`ve found this: https://se.mathworks.com/matlabcentral/fileexchange/28441-hybrid-electric-vehicle-model-in-simulink
Is it possible or am i dreaming too much? :P
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!