Concurrent interaction using functions

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 个评论

functions createWindow and drawBall are missing to check your code.

请先登录,再进行评论。

 采纳的回答

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 个评论

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