Animating a circle inside a rectangle

조회 수: 5 (최근 30일)
David Eufrásio
David Eufrásio 2020년 3월 22일
댓글: David Eufrásio 2020년 3월 28일
The goal is to create an animation that represents an animated (separate successive images separated by a time 'dt') particle (28*R pt, 'R' is the radius, and the position of its center is r=[x;y]) during a time interval 'deltat' within a rectangle (width=a and height=b), with a certain velocity v=[vx;vy]. This particle collides with the 'walls' of the rectangle and conserves its kinetic energy. The collision with the wall x=0 happens in a deltat=(R-r(1))/v(1), and the collision with the wall x=a happens in a deltat=(a-R-r(1))/v(1).
I tried to represent this, but there's always something wrong with the code.
[MY CODE]
/////////////////////////////////////////
a=20
b=10
R=0.5
v=[10;10]
r=[10;5]
vx=v(1)
vy=v(2)
x0=r(1)
y0=r(2)
dt=0.1
deltat=5
X=zeros(1,500)
%x to the right
xright=((a-R-x))/vx
x0 = a/2;
y = b/2;
for i=2:1:deltat
%rectangle
plot([0,a],[0,0],'r-',[a,a],[0,b],'r-',[0,0],[0,b],'r-',[0,a],[b,b],'r-')
hold on
%circle
X(i) = x(i-1) + vx*dt
plot(X, y,'ro','MarkerSize',28*R);
axis ([-10,30,-10,20])
hold off
pause(0.05)
end
/////////////////////////////////////////
My logic was to literally trace the circle's movement (first from the center to the right wall, then to the center again towards the left wall (...) ). Nonetheless, the code does not work.
Thank you.

채택된 답변

darova
darova 2020년 3월 22일
Mistake:
Mistake
Also you shoud have conditions when ball collides:
if (x<0)||(a<x)
vx = -vx; % change sign
end
the same for vy
Add line (similar to yours)
Y(i) = Y(i-1) + vy*dt;
You can also add gravity
vy = vy - 9.8*dt;
  댓글 수: 14
darova
darova 2020년 3월 28일
Why can't you declare deltat inside function?
David Eufrásio
David Eufrásio 2020년 3월 28일
Basically, some steps ahead in the main script the deltat (the time a particle takes to collide with a wall, or with another particle) is calculated for each cycle the code does, and the animation will draw the movement for that deltat. The problem is that sometimes deltat isn't an integer number (it's decimal), and therefore the instruction zeros gives an error.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by