製作如螢幕保護程式會看到的球球動畫,碰到邊界反彈

class ball:

x, y是球的圓心坐標, r是半徑長, R是直徑長, cr是球的顏色, dx, dy是移動的向量分量, bx1, bx2, by1, by2是邊界

在建構子裡面設定坐標、移動向量(用while迴圈,保證向量不為零)、直徑、顏色、邊界值

製作顯示方法(show) 及 移動方法(move)

 

傳入主程式 class mm:

 運用類別陣列,ㄧ次生產10個球物件,在Frame的paint()方法中 實作ball的show(),在Runnable的Run方法中 實作move()。

 

其他還有用到的class有fun跟Init,可以在本網誌裡找到該class的內容


import java.awt.Color;
import java.awt.Graphics;

public class ball {
	/*public var*/
	int x = 0, y = 0, r=0, R=0;Color cr = new Color(0,0,0);
	int dx = 1, dy = 1;
	int bx1=0, bx2=0, by1=0, by2=0;/*boundary*/
	ball(){
		x=fun.Rand(1,1000);y=fun.Rand(1,800);
		r=fun.Rand(5,20);R=2*r+1;
		dx=fun.Rand(-2,2);dy=fun.Rand(-2,2);
		while(dx==0){dx=fun.Rand(-2,2);}
		while(dy==0){dy=fun.Rand(-2,2);}
		cr = new Color(fun.Rand(0,255),fun.Rand(0,255),fun.Rand(0,255));
		bx1=r+2; bx2=1000-r-2; by1=r+28; by2=800-r-2;
	}
	
	void move(){
		x+=dx;y+=dy;
		if((x<=bx1)||(x>=bx2)){dx*=-1;}
		if((y<=by1)||(y>=by2)){dy*=-1;}
	}
	
	void show(Graphics g){
		g.setColor(cr);
		g.fillOval(x,y,R,R);
	}
}

 

import java.awt.*;

public class mm extends Frame implements Runnable{
	/**public var Thread**/
	Thread th=null;
	int num = 10;
	ball[] b = new ball[num];
	
	mm(){
		Init.InitWin(this);
		Init.addWinListen(this);
		
		for(int i=0;i<num;i++)
			b[i] = new ball();
		
		th = new Thread(this);
		th.start();
	}
	
	public static void main(String[] args){
		mm p = new mm();
	}

	/*Override*/
	public void paint(Graphics g){
		for(int i=0;i<100;i++)b[i].show(g);
		}
	
	
	public void run() {
		while(true){
			for(int i=0;i<num;i++)
				b[i].move();
			repaint();
			try{Thread.sleep(3);}catch(Exception e){}
		}
	}
}
arrow
arrow
    文章標籤
    物件導向 動畫
    全站熱搜
    創作者介紹
    創作者 Kuihao 的頭像
    Kuihao

    溫暖午後的金針田__孕育有趣的創新

    Kuihao 發表在 痞客邦 留言(0) 人氣()