Java实现随机动态的小球

2014-11-24 10:09:32 · 作者: · 浏览: 1

package my.test.window;


import java.awt.Frame;


import java.awt.Graphics;


import java.awt.event.*;


import java.awt.*;



public class ShowWidow extends Frame {



private static final int GAME_WIDTH = 800;


private static final int GAME_HEIGHT = 600;



int x,y, vx, vy;


int bounce = -1;



public ShowWidow(){


init();


x= 20;


y = 20;



vx = 20;


vy = 20;


}




private void init() {


lauchFrame();


}



private void lauchFrame(){


this.setSize(GAME_WIDTH, GAME_HEIGHT);


this.setTitle("随机运动小球");


this.addWindowListener(new WindowAdapter(){


public void windowClosing(WindowEvent e){


System.exit(0);


}


});


this.setResizable(false);


this.setBackground(Color.GREEN);


this.setVisible(true);


new Thread(new PaintThread()).start();


}



class PaintThread implements Runnable{



@Override


public void run() {


while(true){


repaint();


try {


Thread.sleep(50);


} catch (InterruptedException e) {


e.printStackTrace();


}


}


}




}



public void paint(Graphics g) {


g.setColor(Color.RED);


g.fillOval(x, y, 20, 20);


x += vx;


y += vy;


if(x<=0){


x = 0;


vx *= bounce;


}else if(x + 20 > GAME_WIDTH){


x = GAME_WIDTH - 20;


vx *= bounce;


}



if(y <= 0){


y = 0;


vy *= bounce;


}else if(y+20 >= GAME_HEIGHT){


y = GAME_HEIGHT - 20;


vy *= bounce;


}


}




public static void main(String[] args){


ShowWidow showwindow = new ShowWidow();


}


}


上面是一个完整的小示例,实现了小球的移动,碰到边界后会朝相反的方向移动,主要是用到了vx和vy向量,值得研究。


游戏中用到的一些知识点:


我们可以求两点之间的夹角,然后设置速度,再使用三角学计算出vx和vy,然后让物体移动。