ZShock
ZShock

Reputation: 255

My C# XNA random() function is not returning the values I'd like it to?

I'm aware that the random() function in C# uses the processor's clock to return its values, soon I had to do some tricks to make it return different values in a short timespan. Now something new has ocurred: I can return multiple different values, but it is not quite "random".

May I explain myself with this picture. I let this piece of code running for a few seconds...

spawnMsCounter += gt.ElapsedGameTime.Milliseconds;
        if (spawnMsCounter > 1)
        {
            spawnMsCounter -= 1;
            random = new Random();
            float x = random.Next(-1, game.Window.ClientBounds.Width);
            int y = random.Next(-1,random.Next(1,game.Window.ClientBounds.Height));
            Coins.Add(new Coin(coinTexture,x,y));
        }

And I got this: http://img62.imageshack.us/img62/4783/khrogbeta20110916154637.png

As you can see, most points spawn in the top part of the screen; why? And how to fix - or create a better code out of - it?

Upvotes: 3

Views: 1108

Answers (2)

Nimrand
Nimrand

Reputation: 1768

You should be reusing your Random objects, but I blieve the reason that the coins tend to spawn towards the top is this line of code:

int y = random.Next(-1,random.Next(1,game.Window.ClientBounds.Height));

You are first generating a random number between 1 and the height of your client, and then using that as the bound for generating another random number that is between -1 and the first value generated. Since the second value will always be less than or equal to the first value generated, lower values are more likely than higher ones (and in fact your picture shows roughly the distribution one would expect). For a uniform distribution, you need:

int y = random.Next(-1,game.Window.ClientBounds.Height);

Upvotes: 2

Cubicle.Jockey
Cubicle.Jockey

Reputation: 3328

Do not create a new Random object every time. Make that a private static or something in the class that you are using this in.

Upvotes: 5

Related Questions