BecomeAPatron

Oops! Dodgy Random Numbers with Deltatime

OK, I just found that I had a random numbers bug in my current code (and, shock horror, in my last 2 released titles (possibly more)). Basically it’s pretty simple and easy to overlook. Let’s say that you want a 20% chance of something occuring per logic cycle so you write some code like this:

If rand(1,100) <= 20 then do something Well that's fine if you call that code a set number of times per frame, say 200. But what if you call it loads of times, because perhaps VSync is off? Well you'll end up with that action occuring way more times than it's supposed to! Of course I use delta time to make sure that my game objects and counters etc don't speed up and go crazy if VSync is off, or if the player goes into windowed mode which may run at any Hz. So basically I need to apply the same principle to the random chance by multiplying the chance by Delta i.e. If rand(1,100) <= 20*Delta then do something This solves the problem. Most of the time delta is 1, but when the framerate is high, delta is often 0 (or close to it) and therefore the random chance is not inflated in such cases. Another thing to watch our for is this: If rand(1,100) > 20*Delta then do something

This looks like chance occurs 80% of the time right? WRONG! If Delta is 0 then 20*0 = 0 so the chance would occur 100% of the time if VSync was off – big bug! So be careful 🙂

4 Responses to “Oops! Dodgy Random Numbers with Deltatime”

  1. Blueskied Games Says:

    Nasty. Easy to overlook.
    Does this mean you get more extra items on PCs with faster graphic cards? 🙂

  2. Grey Alien Games Says:

    Well luckily I was using VSync but if it was forced too off in the graphics card then yes!

  3. Neil Y Says:

    To guard against this sort of thing I play each of my games from start to finish on 3 different machines before release, each with large differences in processing power. This kind of thing usually becomes clear immediately when doing these tests, as long VSync is off and that you aren’t limiting the FPS when you do it. These tests are absolutely essential as it’s very easy to forget to apply delta timing to certain things, and in most cases it will take a long time to realize.

  4. Grey Alien Games Says:

    Yep good tip for sure, thanks. This will happen with future release, but I was uner a bit of time pressure to release Holiday Bonus as it was seasonal – mind you it still did pretty well 🙂

    Hey another amusing cock up is this. I made tweak all the graphics brightness and saturation on my PC and was really happy with it, then after it was released I saw it on a friends TFT and it looked way too bright (to me)! Turns out that I forgot I had my CRT brightness turned down pretty low to play games with nice black and to avoid glaring white in Windows! Doh.