Oops! Dodgy Random Numbers with Deltatime

BlitzMax Forums/BlitzMax Programming/Oops! Dodgy Random Numbers with Deltatime

Grey Alien(Posted 2007) [#1]
OK, I just found that I had a bad random numbers bug to do with making something occur randomly a certain percent of the time that was linked to delta time (well lack of correct application).

You can find out more about what it was and how to avoid it yourself here:

http://greyaliengames.com/blog/oops-dodgy-random-numbers-with-deltatime/

Hope that you find it useful and thus know what to avoid in the future!


sswift(Posted 2007) [#2]
In my games, what I do is rather than have at all times some percentage chance of an action occuring, each time the action occurs, I calculate right then the next time it will occur and then just wait for that time to come around.

So let's say I have my aliens dive at the player. When that occurs, I just store NextDiveTime = Time + Rand(5000, 10000) and then I simply check each frame to see if Time >= NextDiveTime.


Grey Alien(Posted 2007) [#3]
Hey that's an interesting approach + avoids calling random number generator each logic iteration.


sswift(Posted 2007) [#4]
The probability approach is interesting too though.

If you use that method, you don't need to create extra variables, except maybe a single constant to define the probability. My method would require a timekeeper variable and up to two constants if you want to store the min and max times somewhere obvious so they can be easily changed.

That's a big upside, not needing that timer variable. Not only does it make the code cleaner, but you also will never need to initialize it. Or reset it. In my game, if an alien is offscreen and it has to fire, I have to store a new next fire time, or else it will fire immediately when it comes back on the screen. And, if I don't want enemies to fire immediately, I have to calculate the first fire time when they spawn. And that means I have to have the calculation code in two places.

There is a downside to your method though. It's not instantly obvious how often an event will occur. And since the event occurring is truly random, it is possible it will NEVER occur. Also, it is possible an event could occur twice within mere milliseconds.

With my method on the other hand, you have precise control over the minimum time between events, and the maximum time between events.

So while your method is the more beautiful one, mine is more practical. :-)


Grey Alien(Posted 2007) [#5]
If you use that method, you don't need to create extra variables, except maybe a single constant to define the probability
Yes that's how I do it. True it may never occur or may occur twice in a row, but hey, that's random numbers for you :-). Actually with something like If rand(1,100) < 10*Delta we know it occurs randomly 10% of the time (tested each logic iteration), so for a 200 frames per second logic loop we can say that it occurs 20 times per second. That's nice and easy to work out.