When I create several objects of the same type in a loop (let’s say a treasure box is exploding and coins fly out), I’m setting their direction and speed using random functions, but they are not random enough. Many times at least 2 of them have the exact same “random” properties set.
I also tried the method on this site which is somewhat better, but still not good enough: https://scottlilly.com/create-better-random-numbers-in-c/
Any tricks to get around this, a better random generator or maybe a better seed?
Hello Lajbert
I never had this problem before.
I agree with Boot , just déclare only one Random() instance and use NextDouble() each time you want a new random number , I think that will solve your issue.
See my sample code bellow :
Random RND = new Random();
for (int t = 0; t < NB; t++)
{
Px = (float)RND.NextDouble() * TerrainTextureMap.Width * Map.TileSize;
Pz = (float)RND.NextDouble() * TerrainTextureMap.Height * Map.TileSize;
Py = Map.GetHightPos(Px, Pz);
}
When you initialise a new random without giving it a seed it uses the system clock for a seed. If your initialising a new random in a tight loop you will get the same seed and the same values.
So only use one instance of random globally, or create a new instance before your loop.
If you want to have the same random sequence everytime give it the same seed (eg 1000)
Random random = new Random(1000)
This is a common problem if you create a new random in a loop. The safest solution, as mentioned, is to create just one Random object for the whole project. That can get a little problematic if you need random numbers in several places and don’t want a global object. There are several ways to solve it, if that’s a concern you have, but whatever you do, make sure that you don’t create more than one Random object per second (with .NET, you might be able to get it down to 1/ms, or smaller, but 1/second is always safe).
If that still isn’t random enough, there is a ‘more random’ option in the Crypography Library