function pong clc clear all close all global x global y global y1 global y2 global h_rec1 global h_rec2 h_fig=figure; set(h_fig, 'KeyPressFcn', @kpfcn) axis([-10 10 -10 10]); y5=-2; y6=2; y7=-2; y8=2; x1=[-8 -7 -7 -8]; y1=[-6 -6 y5 y7]; h_rec1=patch(x1,y1,'k'); x2=[7 7 8 8]; y2=[6 y8 y6 6]; h_rec2=patch(x2,y2,'k'); x3=[-10 -10 10 10]; y3=[-10 -9 -9 -10]; patch(x3,y3,'r') x4=[-10 10 10 -10]; y4=[9 9 10 10]; patch(x4,y4,'r') hold on x0=5; y0=4; v0x=2; v0y=2; dt=0.005; %v0=sqrt(v0x^2+v0y^2);
b=plot(x0,y0,'go','MarkerSize',10,'MarkerFaceColor','g'); ylim([-10 10]); xlim([-10 10]); x=x0; y=y0; vx=v0x; vy=v0y; e = [0.9 1 1.2]; while(1) x=(x+(vx*dt)); y=(y+(vy*dt)); disp(x); disp(y); if ( y <= -9 || y>= 9 ) vy=-e(randi([1,3]))*vy; end if (y >= y1(1,3) && y<=y1(1,4) && x <= x1(1,3)) vx= -e(randi([1,3]))*vx; vy= -e(randi([1,3]))*vy; if (y >= y2(1,3) && y<=y2(1,4) && x >= x2(1,2)) vx= -e(randi([1,3]))*vx; vy= -e(rand([1,3]))*vy; end end disp([y1(1,3),y1(1,4)]); disp([y2(1,3),y2(1,4)]); set(b,'Xdata',x) set(b,'Ydata',y) pause(0.001) if (y <= y2(1,3) && y>=y2(1,4) && x >= x2(1,2)) vx= -e(randi([1,3]))*vx; vy= -e(rand([1,3]))*vy; end end end function kpfcn(hObject,event) global y1 global y2 global y5 global y6 global y7 global y8 global h_rec1 global h_rec2 switch event.Key case 'uparrow' y2= y2+[1 1 1 1]; case 'downarrow' y2= y2-[1 1 1 1]; case 'w' y1= y1+[1 1 1 1]; case 's' y1= y1-[1 1 1 1]; end set(h_rec1, 'YData', y1) set(h_rec2, 'YData', y2) if y5>9 y5=9; end if y5<-5 y5=-5; end if y6>5 y6=5; end if y6<-9 y6=-9; end end
MATLAB: I’m making a Pong Game and trying to set the limit of the y direction of the paddles to y max to 9 and y min to -9
animationkeypressfcnMATLAB
Best Answer