Matlab bouncing ball in box
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hey, guys I'm new to matlab and I'm working on making a script that will create a 20x20 box and have a ball bounce continously off the walls. The program will ask the user to input the magnitude of the velocity and the angle between the velocity vector and the x-axis. It will then calculate and plot the position of the ball in a graph window.
So far this is what I have. I have the ball bouncing off the right side correctly and the top as well. But the ball isn't traveling far enough to the left and down as well. Here is the code.
set(gca, 'XLim',[-10 10], 'YLim', [-10 10]);
cla
axis square
ball = animatedline('color' , 'r', 'Marker', 'o' , 'MarkerSize',12,'MarkerFaceColor','r');
hx0 = .05
hy0 = .05 / sqrt(2);
hx = hx0;
hy = hy0;
xl = 2 %.02
xr = 9.65
yb = xl;
yt = xr;
x = 1
y = 1
while 1 == 1
if x < xl
hx = hx0
end
if x > xr
hx = -hx0;
end
if y < yb
hy = hy0;
end
if y > yt
hy = -hy0;
end
x = x + hx;
y = y + hy;
clearpoints(ball);
addpoints(ball,x,y);
drawnow;
pause(.01)
end
0 Kommentare
Antworten (3)
Geoff Hayes
am 27 Mai 2021
Bearbeitet: Geoff Hayes
am 27 Mai 2021
Dakota - your axes limits are set as
set(gca, 'XLim',[-10 10], 'YLim', [-10 10]);
but the limits you set in code for the box are different
xl = 2 %.02
xr = 9.65
yb = xl;
yt = xr;
I think that you can either reset the axes limits once you set the above four variables with
set(gca, 'XLim',[xl xr], 'YLim', [yb yt]);
or just set your limits to that of the axes
xl = -10;
xr = 10;
yb = xl;
yt = xr;
Jan
am 27 Mai 2021
Bearbeitet: Jan
am 27 Mai 2021
Your point starts at [1,1], but it changes the direction at this strange limits:
xl = 2; %.02
xr = 9.65;
yb = xl;
yt = xr;
A simplified version with adjusted limits:
axes('XLim',[-10 10], 'YLim', [-10 10], 'NextPlot', 'add');
axis square
hx = 0.05;
hy = 0.05 / sqrt(2);
xl = -9.65;
xr = 9.65;
yb = xl;
yt = xr;
x = 1;
y = 1;
for k = 1:5000 % while 1 == 1
if x < xl || x > xr
hx = -hx;
end
if y < yb || y > yt
hy = -hy;
end
x = x + hx;
y = y + hy;
plot(x,y, '.');
end
0 Kommentare
Scott MacKenzie
am 27 Mai 2021
There are alternatives to animatedline. You can create a ball using rectangle with the curvature property set to 1. But, given the approach you are taking and the issue in your question -- the ball isn't traveling far enough to the left and down as well -- change
xl = 2;
to
xl = -10; % adjust as per marker width
0 Kommentare
Siehe auch
Kategorien
Mehr zu Annotations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!