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 Commento

functions createWindow and drawBall are missing to check your code.

Accedi per commentare.

 Risposta accettata

Jan
Jan il 16 Nov 2018
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 Commento

JC
JC il 18 Nov 2018
Alright i understand how the program flows now. Thank you very much.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su 2-D and 3-D Plots in Centro assistenza e File Exchange

Richiesto:

JC
il 16 Nov 2018

Modificato:

JC
il 20 Nov 2018

Community Treasure Hunt

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

Start Hunting!

Translated by