首页 > 解决方案 > 在协程中使用 Mathf.SmoothDamp() 花费的时间比预期的要长

问题描述

当角色播放蹲伏动画时,我在协同程序中使用 SmoothDamp 逐渐调整角色碰撞器的大小:

void OnRifleIdleToCrouchStart(){
    float idleToCrouchVelocity = -0.01f;
    IEnumerator idleToCrouchColl = smoothHeightChange(idleToCrouchVelocity, 1.45f, 1.2f, 0.38f); //smoothTime is .38 since speed for idle to crouch is 2
    StartCoroutine(idleToCrouchColl);
}

IEnumerator smoothHeightChange(float idleToCrouchVelocity, float targetHeight, float targetCenterY, float smoothTime){
    Debug.Log("smoothHeightChange START " + Time.time);
    while(Math.Round(controller.height, 2) > targetHeight)
    {
        float idleToCrouchVelocityCenter = idleToCrouchVelocity * -1f;
        float newHeight = Mathf.SmoothDamp(controller.height, targetHeight, ref idleToCrouchVelocity, smoothTime);
        float newCenterY = Mathf.SmoothDamp(controller.center.y, targetCenterY, ref idleToCrouchVelocityCenter, smoothTime);
        controller.height = newHeight;
        controller.center = new Vector3(controller.center.x, newCenterY, controller.center.z);

        yield return new WaitForEndOfFrame();
    }
    Debug.Log("smoothHeightChange FINISH " + Time.time);
}

我预计蹲下的时间是 smoothTime(0.38 秒),但比较开始和结束时间表明它实际上需要大约 2 秒。我怀疑这是因为我在等待协程中每一帧的结束,而 SmoothDamp 假设它在每一帧都完成。所以我的 smoothDamp 值实际上需要小于 0.38,与动画过程中每帧剩余的时间成正比。但我不确定我应该通过什么值来修改smoothDamp,因为在动画过程中每一帧的帧时间可能不同(~40 帧)。如何重构协程需要 SmoothDamp 的长度来完成?

谢谢!

标签: c#unity3dcoroutine

解决方案


推荐阅读