Particle animation inside a rectangle

10 views (last 30 days)
So I need to do a circle that it's moving inside a rectangle and colliding with the "walls" of it, with constant velocity. I really don't know hot to do that. I would like to do something like the DVD stand by animation but with a circle and less complex. Can somebody help me?

Accepted Answer

Mark Rzewnicki
Mark Rzewnicki on 20 Mar 2020
What do you have so far?
I wouldn't worry about the animation at this point; there are a bunch of ways to make that happen once you have a good underlying program that tells you where the particle is. An animation example (with random particle positions) might look something like this:
xc=1; yc=2; r=1;
theta = 0:pi/30:2*pi;
x = r * cos(theta) + xc;
y = r * sin(theta) + yc;
circle = plot(x, y,'k');
axis([-20 20 -20 20]);
for k=1:20
rectangle('Position',[-17 -12 35 25]);
circle.XData = x + randi([-10 10],1);
circle.YData = y + randi([-10 10],1);
pause(0.5);
end
What you need to do is set the initial conditions for the particle (position & velocity in the x & y directions) and devise a way to determine its position for the length of the simulation. Something along the lines of:
new x position = old x position + x velocity * time
new y position = old y position + y velocity * time
And you'll need a scheme for handling collisions, which of course will be triggered when the x or y position of the particle (or its edge - if you define the center of the particle don't forget to add the radius back on) equals the x or y borders of the rectangle (think if/else statements there). You could:
  • use trig and come up with arrival/departure angles
  • use a simple scheme like "collisions with the floor and ceiling change the sign of the y velocity, collisions with the walls change the x velocity"
Excited to see what you come up with! I once made a Pong game in VHDL for a digital systems course - similar stuff here.
  2 Comments
Luís Mira
Luís Mira on 20 Mar 2020
Thanks! I tryied to do a "while cycle" which I think that it would give me what I want to define the boundaries but I was not successful unfortunately. I'm trying to solve that problem for some days but I can't do much more than this. I'm kind of a begginer on this :) Your tip was very helpfull tho!
Can you give me your email or something like that to help me a little bit?
Mark Rzewnicki
Mark Rzewnicki on 20 Mar 2020
Edited: Mark Rzewnicki on 20 Mar 2020
--------------@gmail.com
Don't hesitate to reach out!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!