简体   繁体   English

在Windows Forms C#中模拟降雪

[英]Simulating snowfall in Windows Forms C#

I'm quite new in C# and I want to creating something like falling snow (dots) in C# using Windows Forms. 我是C#的新手,我想使用Windows窗体在C#中创建类似落雪(点)的内容。

I was already able to create the snowflakes at the top of the screen (I want to create new dot every 0,1s, at random x-position of Form and write down every snowflake's position into the List(Point) and with every Tick of timer (0,1s) I want the snowflake to change its position by 3px down and 1-3px right) 我已经能够在屏幕顶部创建雪花(我想每隔0,1s在Form的随机x位置创建一个新的点,然后将每个雪花的位置记入List(Point)和计时器(0,1秒),我希望雪花将其位置向下移动3px,向右更改1-3px)

But I have the problem with refreshing the snowflakes positions. 但是我有刷新雪花位置的问题。 I don't know how to acces each snowflake in the List to Randomize its new position. 我不知道如何访问列表中的每个雪花以随机化其新位置。 I tried foreach, but it gives me error, that says I cannot change variable in foreach. 我尝试了foreach,但是它给了我错误,即我无法在foreach中更改变量。

Example: 例:

foreach (var snowflake in snowflakeList)            
            {
               snowflake.Y += 3;
               snowflake.X += moveRandom.Next(1, 4);
            }

Can anyone please tell me how can I divide List(Point) of snowflakes into invdividual snowflakes, so I could change position of every single dot separately? 谁能告诉我如何将雪花的List(Point)划分为单个雪花,以便可以分别更改每个点的位置?

Thank you :-) 谢谢 :-)

The simplest way is just to use the index of the collection: 最简单的方法就是使用集合的索引:

for (int i = 0; i < snowflakeList.Count; i++)            
{
    var snowflake = snowflakeList[i];
    snowflake.Y += 3;
    snowflake.X += moveRandom.Next(1, 4);
    snowflakeList[i] = snowflake;
}

As Andrews answer use a for loop, but as the list is of Points (a value type) you would need to reference the Point in the list directly rather than make a copy of it: 当安德鲁斯回答使用for循环时,但是由于列表是点(值类型),因此您需要直接在列表中引用点,而不是对其进行复制:

for (int i = 0; i < snowflakeList.Count; i++)            
{
    snowflakeList[i].Y += 3;
    snowflakeList[i].X += moveRandom.Next(1, 4);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM