Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How can I apply "damping" to a value

Discussion in 'Scripting' started by Jason210, Apr 13, 2018.

  1. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    131
    Hi

    I have a value x that is modified by another value y every frame. This results in x increasing or decreasing. The value of y can change, as it is itself dependent on other factors.

    The problem is that I don't want x to change immediately in response to a change in y, but slowly. So for example, if x = 2, and y modifies it to 4, I want x to start trending towards 4 with a Bezier-like smoothness, then stop when it reaches 4.

    Is there a pattern or method that can be put to this purpose? Any help would be appreciated.

    /Jason
     
  2. TJHeuvel-net

    TJHeuvel-net

    Joined:
    Jul 31, 2012
    Posts:
    838
    You could multiply y by a value evaluating x in an AnimationCurve
     
  3. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
  5. MBrown42

    MBrown42

    Joined:
    Jan 23, 2018
    Posts:
    86
    Have you thought of Mathf.lerp( float a, float b, float t) ?
    https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html

    First param is the first number, second is the second, and t is how far between you want the result - 0 is the first, 1 is the second. So if you define a speed that is low, multiple by Time.deltatime, you could use it as the third parameter and mess with the speed until you get what you like.

    Just my 2 cents.
    Thanks!
     
  6. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    131
    Thanks everyone.

    I think Baste nailed it with Mathf.SmoothDamp.

    The other suggestions were helpful though.
     
    Last edited: Apr 16, 2018