net: [[../BehaviorTracking/else/笔记系统构建]]
实验要求
完成雪花漫天飞舞的场景(粒子系统),基本步骤如下:
1、构建结构体SNOW;
2、利用随机函数随机生成位置、大小、速度、加速均不相同的雪花;
3、设置定时器;
4、更新每一个雪花的位置;
5、将背景设置为黑色,并消除图像闪烁。
实验步骤:
1. 打开双缓存

2. 构建一个类SNOW,并利用随机函数定义SNOW的生成函数及位置更新函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| Class SNOW
{
public int x, y;
public int size, speed, acceleration;
public SNOW(Random rnd, int panelWidth)
{
size = rnd.Next(5, 20);
speed = rnd.Next(1, 5);
acceleration = rnd.Next(1, 3);
x = rnd.Next(0, panelWidth);
y = rnd.Next(0, -600);
}
public void Update()
{
x += speed;
y += acceleration;
}
}
|
3. 在窗体上定义几个变量用于生成雪花
1 2 3 4 5 6 7 8 9
| List<SNOW> SnowList = new List<SNOW>();
Random rnd = new Random();
int PanelWidth, PanelHeight;
Timer _timer;
|
4. 进行一些初始化的操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public Form1()
{
InitializeComponent();
InitializeTimer();
_Width = ClientSize.Width;
_Height = ClientSize.Height;
}
private void InitializeTimer()
{
_timer = new Timer();
_timer.Interval = 100;
_timer.Tick += Timer_Tick;
_timer.Start();
}
|
5. 在计时器中添加雪花并更新每一个雪花的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| private void Timer_Tick(object sender, EventArgs e)
{
SnowList.Add(new SNOW(rnd, _Width));
for (int i = SnowList.Count - 1; i >= 0; i--)
{
SnowList[i].Update();
if (SnowList[i].y > _Height)
SnowList.RemoveAt(i);
}
Invalidate();
}
|
6. 绘制出雪花和黑色背景。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.Black);
foreach (SNOW snow in SnowList)
{
e.Graphics.FillEllipse(Brushes.White, snow.x, snow.y, snow.size, snow.size);
}
}
|

References