Animating a circle inside a rectangle

5 visualizaciones (últimos 30 días)
David Eufrásio
David Eufrásio el 22 de Mzo. de 2020
Comentada: David Eufrásio el 28 de Mzo. de 2020
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.

Respuesta aceptada

darova
darova el 22 de Mzo. de 2020
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 comentarios
darova
darova el 28 de Mzo. de 2020
Why can't you declare deltat inside function?
David Eufrásio
David Eufrásio el 28 de Mzo. de 2020
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by