这是一段很好的代码,供大家参考和研究
//用粒子模拟瀑布
public class WaterFall implements Runnable
{
final int Max = 1000;
wparticle p[];
int AppletWidth,AppletHeight,XCenter,YCenter;
Image OffScreen;
Graphics drawOffScreen;
Thread pThread;
public void init()
{
setBackground(Color.black);
AppletWidth = getSize().width;
AppletHeight = getSize().height;
p = new wparticle[Max];
for(int i=0; i<Max; i++)
p[i] = new wparticle();
OffScreen = createImage(AppletWidth,AppletHeight);
drawOffScreen = OffScreen.getGraphics();
}
public void start()
{
pThread = new Thread(this);
pThread.start();
}
public void stop()
{
pThread = null;
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.drawImage(OffScreen,0,0,this);
}
public void run()
{
boolean reset = false;
int i, t =0;
while(true)
{
drawOffScreen.clearRect(0,0,AppletWidth,AppletHeight);
drawOffScreen.setColor(Color.white);
drawOffScreen.drawLine(0,15,10,15);
for(i=0; i<Max; i++)
{
drawOffScreen.fillOval((int)p[i].X,(int)p[i].Y,3,3);
p[i].X = p[i].X + p[i].Vx;
if(p[i].X > 10)
{
p[i].Y += p[i].Vy*p[i].time / 1000;
p[i].Vy = (int) 9.8*p[i].time;
p[i].time++;
}
if(p[i].Y > AppletHeight)
{
p[i].reset();
}
}
repaint();
try {
Thread.sleep(100);
}
catch (InterruptedException e) { }
}
}
}
class wparticle
{
double X,Y;
double Vx,Vy;
int time;
public wparticle()
{
reset();
}
public void reset()
{
X = (int) (Math.random() * -40);
Y = (int) (Math.random() * 5 + 10);
Vx = Math.random()*3 + 1.0;
Vy = 0;
time = 0;
}
}