Asteroids

Hi, I just started playing around with OpenGL. I’m creating the classic Asteroids game. I have a problem when creating the actual asteroids.

here’s my constructor


Asteroid::Asteroid()
{
  radius = 2;
  numPts = 8;
  srand(time(0));
  angle = 1 + rand() % 360;
  posX = -10 + rand() % 20;
  posY = -10 + rand() % 20;
}

Then here’s my draw code


void Asteroid::draw()
{

  glTranslatef(posX, posY, 0.0);
  glBegin(GL_LINE_LOOP);
  for (int i=0; i < 360; i+=360/numPts)
  {
    float degInRad = i*DEG2RAD;
    glVertex2f(cos(degInRad)*radius, sin(degInRad)*radius);
  }
  glEnd();
}

and finally in main() in my display function


  for(int i=0; i<numOfAsteroids; i++)
  {
    glPushMatrix();
      if(asteroids[i].getActive())
        asteroids[i].draw();
    glPopMatrix();
  }

The problem is that I draw 10 asteroids in my display func. But their coordinates are all the same. I put that rand() function inside the constructor of each asteroid thinking it would create a set of different coordinates for each asteroid. But what it does instead, is create the same coordinates for all ten asteroids.

help,
mike

Move the srand(time(0)) in your main function or the function that you call once at init.

thanx, that was it :slight_smile: