So I'm trying to create a matrix-like program with "raining green code". Everything has been going well until I decided to throw all of the string instances into a list and draw/update from it. In order to acheive the proper effect I need to randomize a few things.
All the strings are created and stored in the list you see here in a for loop. The interval and dropspeed random numbers change how fast a string falls, and at what speed the individual characters rotate through a sprite sheet.
For some reason though I'm just getting a wall of text that falls all at once and all the sprites are rotating at an equal pace. The classes and their respective functions do work...so the question is what am I doing wrong with my random number initialization?
for (int i = 0; i < (wWidth / 30); i++)
{
Random random = new Random(new System.DateTime().Millisecond);
float randInterval = NextFloat(random);
int dropSpeed = random.Next(1, 7);
_msList.Add(new MatrixString(chinese, randInterval, dropSpeed, dropSpeed, 1.0f, xOff, 10));
xOff = i * 32;
}
You need to create the random
instance outside the for
loop:
Random random = new Random(new System.DateTime().Millisecond);
for (int i = 0; i < (wWidth / 30); i++)
{
float randInterval = NextFloat(random);
int dropSpeed = random.Next(1, 7);
_msList.Add(new MatrixString(
chinese, randInterval, dropSpeed, dropSpeed, 1.0f, xOff, 10));
xOff = i * 32;
}
Within a short running loop, seeding with new System.DateTime().Millisecond
will create the same seed value. Hence, the same random number.
Your loop is "to fast" and so the new Random(new System.DateTime().Millisecond)
will always deliver the same result as each loop is faster then 1ms - the following should work:
Random random = new Random(new System.DateTime().Millisecond);
for (int i = 0; i < (wWidth / 30); i++)
{
float randInterval = NextFloat(random);
int dropSpeed = random.Next(1, 7);
_msList.Add(new MatrixString(chinese, randInterval, dropSpeed, dropSpeed, 1.0f, xOff, 10));
xOff = i * 32;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With