Jump to content
  • Advertisement
Sign in to follow this  
Ferm

rand problem

This topic is 5468 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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).

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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


Share this post


Link to post
Share on other sites
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().

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!