Search Unity

Interpolating a dynamic value

Discussion in 'Scripting' started by beanburgerr, Aug 9, 2019.

  1. beanburgerr

    beanburgerr

    Joined:
    Jan 24, 2016
    Posts:
    3
    Hello! I'm having a problem with interpolating a value that constantly changes - pelvis rotation on x axis for procedural animation. When the character goes up I want them to bend forward and when descending they should bend backward a little. The character now knows when going up or down and somehow choppily bends but I just CAN'T make the movement smooth! I'm no programmer and it's probably something absolutely stupid. I'll be super grateful for any help :(

    Here's the code (clean, without all the interpolation stuff I tried)
    Code (CSharp):
    1. private void Start()
    2.     {
    3.         anim = GetComponent<Animator>();
    4.         InvokeRepeating("PrevPos", 0, 0.2f);
    5.     }
    called from OnAnimatorIK:
    Code (CSharp):
    1.  
    2.         newPelvisRotation = anim.bodyRotation.eulerAngles + whyunotwork;
    3.         anim.bodyRotation = Quaternion.Euler(newPelvisRotation); //<MAKE THIS SMOOTH
    4.     }
    5.  
    6.     void PrevPos()
    7.     {
    8.         previousPositionY = transform.position.y;
    9.         Invoke("CheckPos", 0.2f);
    10.     }
    11.     void CheckPos()
    12.     {
    13.         RaycastHit hitRay;
    14.         Physics.Raycast(transform.position, Vector3.down, out hitRay, 2f);
    15.         groundSlopeAngle = Vector3.Angle(hitRay.normal, Vector3.up);
    16.         if (transform.position.y < previousPositionY)
    17.         {
    18.             groundSlopeAngle = -groundSlopeAngle;
    19.         }
    20.         whyunotwork = Vector3.right * groundSlopeAngle;
    21.     }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
  3. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    When interpolating dynamic value, constantly increate weight over time. Imagine we have a sequnce of X positions recorded as animation keyframes with .5 second step:

    0 1 -1 2 -2 1 -1 0

    This sequnce will move object around 0 with increasing amplitude , then the aplitude wil decrease and object will stop back at 0. Now imagine we want to interpolate it's position to 1 during that animation.

    For that we do:

    Code (CSharp):
    1. private void LateUpdate() {
    2.   x = Mathf.Lerp(x, 1, timeSinceStart / duration);
    3. }
    With this, object will start waving around 0 and stop at 1 smoothly and preserving original animated move.
     
  4. beanburgerr

    beanburgerr

    Joined:
    Jan 24, 2016
    Posts:
    3
  5. beanburgerr

    beanburgerr

    Joined:
    Jan 24, 2016
    Posts:
    3
    Thank you so much, I'll try this!