简体   繁体   中英

How I change ik weight using lerp over time?

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);

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM