Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generation for multiple objects

Tags:

c#

random

xna

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;
}
like image 749
Mike H. Avatar asked Feb 21 '23 18:02

Mike H.


2 Answers

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.

like image 56
Dave M Avatar answered Feb 24 '23 08:02

Dave M


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;
}
like image 39
Christoph Fink Avatar answered Feb 24 '23 07:02

Christoph Fink