Home > database >  How I change ik weight using lerp over time?
How I change ik weight using lerp over time?

Time:11-25

void OnAnimatorIK()
    {
        if (changeWeight == true && change == false)
        {
            StartCoroutine(changeValueOverTime(1, 0, 5));

            change = true;
        }
    }

And

IEnumerator changeValueOverTime(float fromVal, float toVal, float duration)
    {
        float counter = 0f;

        while (counter < duration)
        {
            if (Time.timeScale == 0)
                counter  = Time.unscaledDeltaTime;
            else
                counter  = Time.deltaTime;

            float val = Mathf.Lerp(fromVal, toVal, counter / duration);

            animator.SetLookAtWeight(val, val, val, val, val);

            yield return null;
        }
    }

The problem is that changing SetLookAtWeight value/s can be done only inside OnAnimatorIK

I want it slowly return to natural look after x seconds.

If I'm trying to change the SetLookAtWeight inside the IEnumerator changeValueOverTime in the editor I'm getting a message in the console :

Setting and getting Body Position/Rotation, IK Goals, Lookat and BoneLocalRotation should only be done in OnAnimatorIK or OnStateIK UnityEngine.Animator:SetLookAtWeight (single,single,single,single,single)

On the line :

animator.SetLookAtWeight(val, val, val, val, val);

CodePudding user response:

OnAnimatorIK is called repeatedly as part of the Animator Update Loop within the Physics block similar to FixedUpdate.

I think basically you would rather do this

bool isChanging;
float counter;

void OnAnimatorIK()
{
    if (changeWeight)
    {
        if (Time.timeScale == 0)
            counter  = Time.unscaledDeltaTime;
        else
            counter  = Time.deltaTime;

        var val = Mathf.Lerp(1f, 0f, counter / 5f);

        animator.SetLookAtWeight(val, val, val, val, val);

        if(counter >= 1f) changeWeight = false;
    }
}
  • Related