First, this is a UI that lets an object bounce back and forth inside the frame,
The rebound in the boundary is in accordance with the conservation of the momentum of physics, that is, ideal.
Prepare for the next collision mechanism and try to add some interesting algorithms.
Anyway, the writing is very bad, are not allowed to laugh.
First, the method class
Packagetest;Importjava.awt.*;ImportJava.awt.event.WindowAdapter;Importjava.awt.event.WindowEvent; Public classMyFrameextendsframe{Image img=gameutil.getimage ("Images/sun2.jpg"); Public Static Final intgame_width=500; Public Static Final intgame_height=500; Public voidLaunchframe () {setSize (constant.game_width,constant.game_height); SetLocation (100,100); SetVisible (true); NewPaintthread (). Start (); Addwindowlistener (NewWindowadapter () {@Override Public voidwindowclosing (windowevent e) {system.exit (0); } }); } Private Doublex=100,y=100; Private DoubleDegree=3.14/3; Private Booleanleft=false; Private Booleanup=false; Private Doublespeed=10; @Override Public voidPaint (Graphics g) {G.drawimage (img, (int) x, (int) Y,NULL); if(speed>0) { speed-=0.05; }Else{ speed=0; } x+=speed*Math.Cos (degree); Y+=speed*Math.sin (degree); if((x>500-50) | | (x<20) ) {degree=math.pi-degree; } if((y>300-50) | | (y<20) ) {degree=-degree;; } } classPaintthreadextendsthread{ Public voidrun () { while(true) {repaint (); Try{Thread.Sleep (40); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } } Public Static voidMain (string[] args) {MyFrame GF=NewMyFrame (); Gf.launchframe (); }}
Second, the window class
Packagetest;ImportJava.awt.Graphics;ImportJava.awt.Image; Public classGameframeextendsmyframe{Image img=gameutil.getimage ("Images/sun2.jpg"); Private Doublex=100,y=100; Private DoubleDegree=math.pi/3; Private Booleanleft=false; Private Booleanup=false; Private Doublespeed=10; @Override Public voidPaint (Graphics g) {G.drawimage (img, (int) x, (int) Y,NULL); if(speed>0) { speed-=0.1; }Else{ speed=0; } x+=speed*Math.Cos (degree); Y+=speed*Math.sin (degree); if((x>500-50) | | (x<20) ) {degree=math.pi-degree; } if((y>300-50) | | (y<20) ) {degree=-degree;; } } classPaintthreadextendsthread{ Public voidrun () { while(true) {repaint (); Try{Thread.Sleep (40); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } } Public Static voidMain (string[] args) {gameframe GF=NewGameframe (); Gf.launchframe (); }}
It's such a stupid interface.
He can move the ball, move it, don't laugh.
The UI of an object bouncing back and forth inside a frame