Creating a 2D moving object

조회 수: 23 (최근 30일)
Joe Bird
Joe Bird 2015년 9월 30일
댓글: Atakan Botasun 2021년 6월 13일
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?

채택된 답변

Mike Garrity
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
YUZHE LIU
YUZHE LIU 2020년 12월 5일
Then how to control its speed?
Atakan Botasun
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
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

카테고리

Help CenterFile Exchange에서 Lighting, Transparency, and Shading에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by