I’ve finished the 3rd person combat series, and I was wondering why do we pass the deltaTime everywhere around the stateMachine instead of retrieving it from Time.deltaTime itself each time.
Isn’t this unnecessary caching, or am I missing a key concept for why it’s better to pass around the deltaTime value?
I don’t know why Nathan used it like this, but the way I always pictured it was that if you don’t pass it and directly use Time.deltaTime you have tied yourself to that value. Passing it in affords you more control and allows you to pass different values, should you want to. For example, I could pass Time.deltaTime * 2f and now that state machine runs at double speed. Half speed if I pass Time.deltaTime * 0.5f
Yes, but this could also be accomplished with Time.timeScale, no worries no fuss.
The real reason is that the standard State pattern was created as more of a universal – outside of any specific programming language or environment. In Java, for example, you need to calculate deltaTime yourself. In Unreal, the actual delta time is passed directly to the Tick() function (very much like we’re using it here in the 3rd person course.)
You could skip the deltaTime parameter if you wished. Time.deltaTime is highly optimized so there’s really not a lot of difference in execution between referencing Time.deltaTime directly or passing it around like a party favor.
I’ve found some things really belong in the fixed update (almost anything to do with physics, like say… movement!). I’ve taken to caching the input and calculating the movement direction in Tick() as a raw value (i.e. not scaled by deltaTime) and then making the actual move in an added FixedTick() that I added to the State() pattern for my experiments. FixedTick is, of course, called during FixedUpdate() and as I personally like the passing the value pattern, I pass it the fixedTick as well.
Fun fact, however: For several versions now, the value of deltaTime is entirely dependent on which phase the game’s life cycle is active… so while the Update() is running, Time.deltaTime == the time since the last Update() frame. while in the FixedUpdate(), Time.deltaTime == the physics fixed time. Since the game knows what phase you’re in when you call Time.deltaTime, it’s always the right value. Probably they did this because so many programmers were getting the two confused.
Agreed, if I want the whole game to run at double or half speed. If I cast a ‘slow’ spell on an enemy, that enemy’s value could be affected in this way. Not saying this is the way, just pictured it being a reason for forever.
I like passing the value. I try to make functions and methods that have everything they need instead of getting it from elsewhere. In the case of the delta times, though, this isn’t such a big deal 'cos the state of the delta time won’t change during a frame. If I’m unit testing a function, I can’t predict the result if it uses Time.deltaTime, but I can if I pass the value.