Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Mathf.SmoothDamp() work? what is it algorithm?

I was wondering how SmoothDamp works in unity. I'm trying to re-create the function outside unity but the thing is I don't know how it works.

like image 248
inhumane personal Avatar asked Sep 16 '25 06:09

inhumane personal


1 Answers

From Unity3d C# reference source code:

// Gradually changes a value towards a desired goal over time.
        public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, [uei.DefaultValue("Mathf.Infinity")]  float maxSpeed, [uei.DefaultValue("Time.deltaTime")]  float deltaTime)
        {
            // Based on Game Programming Gems 4 Chapter 1.10
            smoothTime = Mathf.Max(0.0001F, smoothTime);
            float omega = 2F / smoothTime;

            float x = omega * deltaTime;
            float exp = 1F / (1F + x + 0.48F * x * x + 0.235F * x * x * x);
            float change = current - target;
            float originalTo = target;

            // Clamp maximum speed
            float maxChange = maxSpeed * smoothTime;
            change = Mathf.Clamp(change, -maxChange, maxChange);
            target = current - change;

            float temp = (currentVelocity + omega * change) * deltaTime;
            currentVelocity = (currentVelocity - omega * temp) * exp;
            float output = target + (change + temp) * exp;

            // Prevent overshooting
            if (originalTo - current > 0.0F == output > originalTo)
            {
                output = originalTo;
                currentVelocity = (output - originalTo) / deltaTime;
            }

            return output;
        }
like image 188
Hamid Yusifli Avatar answered Sep 17 '25 19:09

Hamid Yusifli