I do understand Time.deltaTime is creating shots independent of frames.
Actually, it’s a bit different. Shots are created when (Random.value < probability)
is evaluated to true
.
The variable name probability
is probably a bit confusing because it’s not the actual probability.
Update() gets called every frame. According to Unity’s API, Time.deltaTime
returns “[t]he time in seconds it took to complete the last frame (Read Only)”. The frame time is not constant.
Random.value
returns a “random” float value between 0 and 1.0.
Example:
Frame 1 took 0.25 seconds. 0.25f * 0.5f = 0.125f.
Random.value returns 0.7f.
Frame 2 took 0.12 seconds. 0.12f * 0.5f = 0.06f.
Random.value returns 0.1f.
Frame 3 took 0.32 seconds. 0.32f * 0.5f = 0.16f.
Random.value returns 0.14f.
Fire().
probability
is (the time the last frame took for its completation) * (0.5f), hence a fraction of shotsPerSecond
. It does not have anything to do with probability since a higher value (below 1.0f) does not make it more or less likely to call Fire(). Call the probability variable whatever you like.
Does that make sense to you?
To find out whether probability
has a probability of 80% to be higher than Random.value
, add some Debug.Logs in your code to note the values of probability
and Random.value
for a few frames and calculate the actual probability based on the return value of (Random.value < probability)
, which is either true
or false
.