I am generating rectangles with given random numbers in this class.
class Rect
{
double x;
double y;
public Rect(double _x, double _y)
{
x = _x;
y = _y;
}
public void Draw()
{
Gl.glBegin(Gl.GL_QUADS);
Gl.glVertex2d(x + (-0.05d), y + (-0.05d));
Gl.glVertex2d(x + (-0.05d), y + (0.05d));
Gl.glVertex2d(x + (0.05d), y + (0.05d));
Gl.glVertex2d(x + (0.05d), y + (-0.05d));
Gl.glEnd();
}
}
I call it in Paint function.
private void simpleOpenGlControl1_Paint(object sender, PaintEventArgs e)
{
Gl.glClearColor(0, 1, 0, 0);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
for (int i = 0; i < 4; i++)
{
rand = new Random();
double x = 2 * rand.NextDouble() - 1;
double y = 2 * rand.NextDouble() - 1;
rect= new Rect(x,y);
rect.Draw();
}
}
Everything looks fine but there is something wrong. I cant see the all rectangles. Some of them are missing. But if I toggle breakpoint somewhere or put the MessageBox.Show(x+" "+y); code works fine and shows me the number of rectangles what i want. I think my code is true but something wrong about OpenGL. I am using Tao Framework.
My guess is the problem is with this bit of code:
You are creating a new
Randominstance in every iteration of your loop and then use that instance to generate two random values. The sequence of values generated byRandomdepends on the seed that was used to initialize theRandom. According to the documentation of the constructor used here:That is, if your loop runs fast enough, the different instances of
Randomin your loop will be initialized with the same seed, causing them to generate the samexandyvalues: the rectangles then overlap and appear to be missing. This also explains why your code is working if you interrupt it using breakpoints or messages boxes.Edit: the best solution to this problem is to create a single
Randominstance outside of your loop, by initializingrandbefore yourforstatement or (as a class member) in the constructor of your class for example.