0

Coming from an iOS background I struggle to move a simple GameObject from A to B in 2D. Is there anything like animateWithDuration(duration: NSTimeInterval, animations: () -> Void, completion: ((Bool) -> Void)?)

I think it's inconvenient to change the transform in update. And I can't use Animation View and Animator because it's not possible to change the target position with this tool.

zeiteisen
  • 7,078
  • 5
  • 50
  • 68

1 Answers1

0

Coming from an iOS background too, i'd suggest the following :

class AnimationModule: MonoBehaviour
{

    public delegate void AnimationBlock(float progress);

    public Task animateWithDuration(float duration, AnimationBlock animation, Action completion)
        {
            StartCoroutine(coroutine__animation(duration, animation, delegate
            {
                completion();
            }));

            return Task.Delay(millisecondsDelay: (int)(duration * 1000));
        }

    private IEnumerator coroutine__animation(float duration, AnimationBlock animation, Action completion)
        {
            float startingTime = Time.time;
            float timeCounter  = startingTime;

            while (timeCounter < (startingTime + duration))
            {
                float p = (timeCounter - startingTime) / duration;
                animation(p);
                timeCounter = Time.time;
                yield return null;
            }

            completion();
        }
}

which would then be used this way:

Task anim1 = GetComponent<AnimationModule>().animateWithDuration(duration: 2.0f, animation: (float p) => {

                                    card.transform.localPosition = position_from + p * (new Vector3(100, 0, 0));

                                }, completion: () => {

                                    Debug.Log("animateWithDuration, completion");

                                });

given that the important, to answer the question, is to get closer to iOS style.

It works but I don't know if it behaves well performance-wise.

I use the experimental Mono in order to use Task and the like.

ZpaceZombor
  • 877
  • 1
  • 10
  • 8