Why does Mathf.SmoothDamp() require an accumulator (currentVelocity)?

It’s really annoying to have to create a private variable for every float value that I want to smoothly change, although I understand after seeing the code behind the method why it is necessary.

But, Animator.SetFloat() basically does the same thing as SmoothDamp when you pass it a dampTime and deltaTime, but only for setting values to a mecanim variable, but it does it without having to declare unwieldy private variables for every variable you want to use it on!

How does it work, and why can’t we have a SmoothDamp that works like it, but for regular floats?

1 Like

10 years later… It would have been great if they made this parameter optional.

1 Like

The state needs to be stored somewhere. In the case of the animator, it already has its parameters defined and can just keep track of the transition state as part of that. However, the Mathf functions are pure, they can work anywhere at any time and only work with the inputs you provide as parameters. It has no context of the values you give it and therefore also cannot internally store any related data.

The SmoothDamp state needs to be stored somewhere. Since it can be called with any variable as input (which makes it very flexible and work in all kinds of contexts), it’s up to the caller to provide the storage. This cannot be changed without sacrificing some of its flexibility and it will ultimately just hide the variable from you, as is the case with animator parameters.

You could wrap SmoothDamp in a struct that contains the velocity parameter. You still need to declare the struct as a field but you then can define a method on it that doesn’t need to take the velocity parameter, simplifying the call sites.

Also, SmoothDamp is dynamic, which means it can deal with the target position changing constantly. In cases where start/end/duration are known ahead of time, you can just Lerp with an easing. Then you don’t need any additional state and don’t need to declare any fields.