} [/code]
But when i use it like this: QuizGraphic::initializeDatabase();
Sprite* champ = QuizGraphic::getRandChamp();
champ->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2));
this->addChild(champ, 4);
It always returns the first object??
Why?
Thanks!
The random function is part of Map, neither Vector nor vector:
/**
* Gets a random object in the map.
* @return Returns the random object if the map isn't empty, otherwise it returns nullptr.
*/
V getRandomObject() const
{
if (!_data.empty())
{
ssize_t randIdx = rand() % _data.size();
const_iterator randIter = _data.begin();
std::advance(randIter , randIdx);
return randIter->second;
}
return nullptr;
}
At multiple calls? After game restart?
Step into the function and check the generated number of the PRNG.
The function is not seeding the pseudo random number generator. It will always generate the same sequence. If the sequence begins with 0, it will always generate 0 at game restart. If you don’t seed the PRNG, it’s seeded with srand(1). This is an overlook with the API design. You need to seed it yourself or use other mechanisms.