rand problem
Hi
I am writing a space invaders like game, and I want the aliens to fire randomly. I call srand(time(0)) at the beginning.
For each frame and each alien I do this:
... Alien::Update()
{
if ( (rand()%100) < 40 )
return FIRE;
else
return NO_FIRE;
}
But all aliens fire at the same time.
(Sometimes it works, but when I restart the computer it fails
again, so the rest of the code is correct)
I am thankful for any help.
Are you sure that you only call srand() at the start of your app? This sort of thing always happens if you call srand() repeatedly. If the RNG gets reset between calls to Alien::Update() then the result will always be the same (because time() will return the same value for a second).
Quote:Original post by Evil Steve
Are you sure that you only call srand() at the start of your app? This sort of thing always happens if you call srand() repeatedly. If the RNG gets reset between calls to Alien::Update() then the result will always be the same (because time() will return the same value for a second).
Ah! That could be it! Is it, OP?
Adding
Sleep(1);
before the if case makes it work, so there´s an issue with calling rand() without a time delay.
Either something calls srand or... =( I dont know
Sleep(1);
before the if case makes it work, so there´s an issue with calling rand() without a time delay.
Either something calls srand or... =( I dont know
Quote:Original post by Ferm
Adding
Sleep(1);
before the if case makes it work, so there´s an issue with calling rand() without a time delay.
Either something calls srand or... =( I dont know
Something must be seeding the RNG then. Try using a different RNG, such as the mersianne twister. The standard C rand() function will work no matter how quickly you call it.
Trace into srand() the first time you call it, and put a breakpoint on the first line. Then see if anything else tries to call srand().
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement