I am working on a smooth terrain generation algorithm in C# and using XNA to display the data.
I am making it so it creates a new point halfway between each point per iteration, at a random height between the two. This works OK, and I have set it so that on the second iteration it chooses a random point like in slide two, rather than trying to make a new point between points that are on the same axis.
What is happening is that the loop is using the same random value from the previous iteration: https://i.stack.imgur.com/UmWr7.png
This is not ideal obviously, as it is not a proper random generation.
If I use a Thread.Sleep(20) after each point generation it works correctly: https://i.stack.imgur.com/KziOg.png
I don’t want to have to use the Sleep workaround if possible as it is very slow, and I would like to use this in real-time. I’m pretty sure this has something to do with the C# garbage collector.
Here is my Get Point Code
Random r = new Random();
int x = (p1.X + p2.X) / 2;
int y;
if (!initial)
y = r.Next(Math.Min(p1.Y, p2.Y), Math.Max(p1.Y, p2.Y));
else
y = r.Next(Math.Min(p1.Y, p2.Y) - Game1.screenHeight / 2, Math.Max(p1.Y, p2.Y) + Game1.screenHeight / 2);
return new Point(x, y);
Is the garbage collection a part of the issue?
Any suggestions or solutions on solving this??
Probably you are creating a new Random object in a loop.
Try to create only one instance of Random at program startup, then re-use it. If you have multiple threads, then you could use one random object per thread.