Filter löschen
Filter löschen

Erase bouncing ball drawn on GUI so there is only one drawn ball on GUI at a time

1 Ansicht (letzte 30 Tage)
Hey guys, I'm working on this quick project that has a ball bouncing off all the walls continously. I basically have everything running as I want it, but when I draw the ball on the GUI my old drawn balls stay on GUI as well. How could I delete it so there is only one ball drawn on the GUI at a time. This is what I have.
set(gca, 'XLim',[-10 10], 'YLim', [-10 10]);
cla
axis square
ball = animatedline('color' , 'r', 'Marker', 'o' , 'MarkerSize',12,'MarkerFaceColor','r');
theta = pi/6; % Sets Theta
V = 5; %Sets value of V
[x,y,t] = startBall(V,theta,ball); %Calls function to return x,y,t
xr = 10; % x right
xl = -10; % x left
yt = xr; % y top
yb = xl; % y bottom
function[x,y,t] = startBall(V,theta,ball)
dt =0.1 ; % sets time as 0.1
Vx = V * cos(theta);
Vy = V * sin(theta);
x0 = 0; %initial x position
y0 = 0; %initial y position
x = x0;
y = y0;
t = 0; % Time
while 1 == 1
if x(end) > 10 && y(end) > 10 || x(end) < -10 && y(end) < -10 %Condition of the ball hittin CORNER
Vx = -1*Vx %Change Vx velocity from hitting corner
Vy = -1 * Vy; %Change Vy velocity from hitting corner
elseif x(end) > 10 || x(end) < -10 % Checks if Ball is hitting top or bottom
Vx = -1 * Vx;
elseif y(end) > 10 || y(end) < -10 %Checks if ball is hitting left or right
Vy = -1 * Vy;
end
x(end + 1) = x(end) + Vx * dt; % UPDATES X VAL
y(end + 1) = y(end) + Vy * dt; % UPDdATES Y VAL
t(end + 1) = t(end) + dt; %UPDATES T VAL
clearpoints(ball);
addpoints(ball,x,y);
drawnow;
pause(.01)
end
end
  3 Kommentare
Adam Danz
Adam Danz am 28 Mai 2021
I would just plot the ball once outside of the loop and then update its xdata & ydata values within the loop.
Jan
Jan am 28 Mai 2021
Just a hint: This can be simplified:
if x(end) > 10 && y(end) > 10 || x(end) < -10 && y(end) < -10 %Condition of the ball hittin CORNER
Vx = -1*Vx %Change Vx velocity from hitting corner
Vy = -1 * Vy; %Change Vy velocity from hitting corner
elseif x(end) > 10 || x(end) < -10 % Checks if Ball is hitting top or bottom
Vx = -1 * Vx;
elseif y(end) > 10 || y(end) < -10 %Checks if ball is hitting left or right
Vy = -1 * Vy;
end
to
if x(end) > 10 || x(end) < -10 % Checks if Ball is hitting top or bottom
Vx = -Vx;
end
if y(end) > 10 || y(end) < -10 %Checks if ball is hitting left or right
Vy = -Vy;
end

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements 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!

Translated by