Search code examples
c++arraysspritesfml

Sprite array loop only shows 1 element


Trying to get 4 clouds to move across the screen left to right. When I execute I can see all 4 clouds are drawn at the positions given in the code. But after game starts only one cloud is moving across the screen; the other 3 never show.

const int NUM_CLOUDS = 4;
Sprite clouds[NUM_CLOUDS];
int position = 0;

In main:

Texture textureCloud;
textureCloud.loadFromFile("graphics/cloud.png");
for (int i = 0; i < NUM_CLOUDS; i++)
{
    clouds[i].setTexture(textureCloud);
    clouds[i].setPosition(0, position);
    position += 100;
}
bool cloudsActive[NUM_CLOUDS];
for (int i = 0; i < NUM_CLOUDS; i++)
{
    cloudsActive[i] = false;
}
float cloudSpeed[NUM_CLOUDS];
for (int i = 0; i < NUM_CLOUDS; i++)
{
    cloudSpeed[i] = 0.0f;
}

for (int i = 0; i < NUM_CLOUDS; i++)
{
   if (!cloudsActive[i])
   {
      srand((int)time(0) * 30);
      cloudSpeed[i] = (rand() % 200);
      srand((int)time(0) * 30);
      float height = (rand() % 450) - 150;
      clouds[i].setPosition(-200, height);
      cloudsActive[i] = true;
   }
   else
   {
      clouds[i].setPosition(clouds[i].getPosition().x + (cloudSpeed[i] * dt.asSeconds()), clouds[i].getPosition().y);
      if (clouds[i].getPosition().x > 1920)
      {
         cloudsActive[i] = false;
      }
   }

}


Solution

  • In your code, you are srand-ing every time before you rand. You're probably seeding with the same number every time, because not enough time has passed between calls to srand to change the number. Calling rand() depends deterministically, usually, on the random seed. This means if you call rand() multiple times, each time setting the seed to the same number, you'll get the same number back from rand(). This makes all the clouds get the same parameters, so they display right on top of one another, and you only see them as one cloud. To fix, call srand() only once near the beginning of your program. Also, as @ColonD said, you should be using C++ random numbers if you're in C++11 or newer: https://en.cppreference.com/w/cpp/header/random .