Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/XNA pseudo-Random number creation

The c#/XNA process for creating random numbers is pretty quick and easy, however, it is quite possibly the worst distributing random number generator I have ever seen. Is there a better method that is easy to implement for c#/XNA?

rand.Next() just doesn't suit my needs.

from:

static private Random rand = new Random();

I randomly place objects, all over my program. sometimes 10, sometimes 200.

When calling for random objects (the x val and y val are both random on a 2d plane), they group. The generation code is clean and calls them good, iterated cleanly and pulls a new random number with each value. But they group, noticeably bad, which isn't very good with random numbers after all. I'm intermediate skill with c#, I crossed over from as3, which seemed to handle randomness better.

I am well-aware that they are pseudo random, but C# on a windows system, the grouping is grotesque.

like image 466
SimpleRookie Avatar asked Oct 10 '22 20:10

SimpleRookie


1 Answers

Can you use System.Security.Cryptography.RandomNumberGenerator from XNA?

var rand = RandomNumberGenerator.Create();
byte[] bytes = new byte[4];

rand.GetBytes(bytes);

int next = BitConverter.ToInt32(bytes, 0);

To get a value within a min/max range:

static RandomNumberGenerator _rand = RandomNumberGenerator.Create();

static int RandomNext(int min, int max)
{
    if (min > max) throw new ArgumentOutOfRangeException("min");

    byte[] bytes = new byte[4]; 

    _rand.GetBytes(bytes);

    uint next = BitConverter.ToUInt32(bytes, 0);

    int range = max - min;

    return (int)((next % range) + min);
}
like image 97
Jeff Ogata Avatar answered Oct 18 '22 07:10

Jeff Ogata