# Matlab bouncing ball in box

조회 수: 22(최근 30일)
Dakota Nielsen 2021년 5월 27일
편집: Jan 2021년 5월 27일
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);
drawnow;
pause(.01)
end

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

### 답변(3개)

Geoff Hayes 2021년 5월 27일
편집: Geoff Hayes 2021년 5월 27일
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;
##### 댓글 수: 1표시숨기기 없음
Dakota Nielsen 2021년 5월 27일
Thank you so much!

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

Jan 2021년 5월 27일
편집: Jan 2021년 5월 27일
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표시숨기기 이전 댓글 수: -1

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

Scott MacKenzie 2021년 5월 27일
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

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

### Community Treasure Hunt

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

Start Hunting!

Translated by