Coroutines and while loop

前端 未结 3 1512
说谎
说谎 2021-01-27 06:51

I have been working on a object movement along a path Which i have been geting from Navmesh Unity3d I am using coroutine in which i controled it with while loop as i can show

3条回答
  •  有刺的猬
    2021-01-27 07:36

    As an alternative, you could utilize Unity's AnimationCurve class to map out all kinds of super smooth animation types easily:

    You can define the curves in the inspector, or in code

     public AnimationCurve Linear
    {
        get
        {
            return new AnimationCurve(new Keyframe(0, 0, 1, 1), new Keyframe(1, 1, 1, 1));
        }
    }
    

    And you can define useage in a coroutine as such:

    Vector2.Lerp (startPos, targetPos, aCurve.Evaluate(percentCompleted));
    

    Where "percentCompleted" is your timer/TotalTimeToComplete.

    A full example of lerping can be seen from this function:

        IEnumerator CoTween(RectTransform aRect, float aTime, Vector2 aDistance, AnimationCurve aCurve, System.Action aCallback = null)
    {
        float startTime = Time.time;
        Vector2 startPos = aRect.anchoredPosition;
        Vector2 targetPos = aRect.anchoredPosition + aDistance;
        float percentCompleted = 0;
        while(Vector2.Distance(aRect.anchoredPosition,targetPos) > .5f && percentCompleted < 1){
            percentCompleted = (Time.time - startTime) / aTime;
            aRect.anchoredPosition = Vector2.Lerp (startPos, targetPos, aCurve.Evaluate(percentCompleted));
            yield return new WaitForEndOfFrame();
            if (aRect == null)
            {
                DeregisterObject(aRect);
                yield break;
            }
        }
        DeregisterObject(aRect);
        mCallbacks.Add(aCallback);
        yield break;
    }
    

    Check out this Tween library for more code examples: https://github.com/James9074/Unity-Juice-UI/blob/master/Juice.cs

提交回复
热议问题