I'm coding a program that allows objects to bounce within a window. I have successfully gotten one ball to bounce within it. But when I try to add a second ball, only the first ball moves.
This is the function that allows the object to rebound a wall and it does this indefinitely (While loop) I'm pretty sure the second objcet doesnt show up because the first function is running forever while the while loop is being run (no pun intended). So how do i get the second object to appear and to move concurrently with the first object?
function bounce = bounceFunc(obj, addx,addy,x,y)
%CREATE A FUNCTION OF THIS SO THAT YOU CAN REUSE IT FOR MULTIPLE BALLS
while (x >=0 & x <= 500) & (y >= 0 & y <= 500)
%while the ball is within the window. (extra tolerances???)
%retrieves position for following if statements to determine direction
[x y] = getCenter(obj)
if y >= 480
addy = -addy
end
if y <= 20
addy = -addy
end
if x >= 480
addx = -addx
end
if x <= 20
addx = -addx
end
xMove(obj,addx)
yMove(obj,addy)
redraw
end
end

1 件のコメント

KSSV
KSSV 2018 年 11 月 16 日
functions createWindow and drawBall are missing to check your code.

サインインしてコメントする。

 採用された回答

Jan
Jan 2018 年 11 月 16 日

1 投票

You have to modify the code of bounceFunc to accept arrays for all inputs:
function bounce = bounceFunc(obj, addx,addy,x,y)
n = numel(obj); % Number of objects
%CREATE A FUNCTION OF THIS SO THAT YOU CAN REUSE IT FOR MULTIPLE BALLS
while all((x >=0 & x <= 500) & (y >= 0 & y <= 500))
for k = 1:n
[x y] = getCenter(obj(k)); % You overwrite the inputs x and y here?!
if y >= 480
addy(k) = -addy(k)
end
if y <= 20
addy(k) = -addy(k)
end
if x >= 480
addx(k) = -addx(k)
end
if x <= 20
addx(k) = -addx(k)
end
xMove(obj(k),addx(k))
yMove(obj(k),addy(k))
end
redraw
end
end
Now create the balls before calling the bounceFunc equivalently:
obj(1) = drawBall(xc, yc, rad, col)
[x(1), y(1)] = getCenter(obj(1))
...
obj(2) = drawBall(xc, yc, rad, col)
[x(2), y(2)] = getCenter(obj(2))
etc.

1 件のコメント

JC
JC 2018 年 11 月 18 日
Alright i understand how the program flows now. Thank you very much.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で 2-D and 3-D Plots についてさらに検索

質問済み:

JC
2018 年 11 月 16 日

編集済み:

JC
2018 年 11 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by