気ままなUnityエンジニアブログ

新米Unityエンジニアが送る解説アウトプットブログです。Twitter : @UjinUnity

MENU

【Unity】Dotweenで行ったり来たりするアニメーション作成

スポンサーリンク

f:id:Wojtek:20190910005754g:plain

今回はDotweenを使用して行き帰りアニメーションを作ります。



スクリプトを実装しましょう。
今回はMoveAnimation.csを作成します。



using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class MoveAnimation : MonoBehaviour {

    public RectTransform m_Img;

    private Tween m_AnimeTw;

    void Start () {
        this.m_Img.anchoredPosition = new Vector2 (-150f, 0f);

    }

まずは初期化部分を作成しました。
次はDotweenを使って左右に動くアニメーションを実装しましょう。

private void fadeInAnimation () {

        this.m_AnimeTw = m_Img.DOAnchorPosX (150f, 1f)
            .SetEase (Ease.Linear)
            .OnComplete (() => {

            })
            .OnKill (() => {

            });
    }

    private void fadeOutAnimation () {
        this.m_AnimeTw = m_Img.DOAnchorPosX (-150f, 1f)
            .SetEase (Ease.Linear)
            .OnComplete (() => {

            })
            .OnKill (() => {

            });
    }

上記を実装するとこのような動作になります。

f:id:Wojtek:20190910005748g:plain

左右に動くようになりましたね。

ですが、左右それぞれの移動アクションを連続して起こすとこのようになります。



f:id:Wojtek:20190910005751g:plain

これはこれで面白い動きですが、一つのアニメーション中に別のアニメーションが動いて欲しくない時があると思います。

そのため、アニメーション管理用のフラグを追加してみましょう。

private void fadeInAnimation () {

        if (this.isFadeIn)
            return;

        this.isFadeIn = true;
        this.isFadeOut = true;

        this.m_AnimeTw = m_Img.DOAnchorPosX (150f, 1f)
            .SetEase (Ease.Linear)
            .OnComplete (() => {
                this.isFadeOut = false;
            })
            .OnKill (() => {

            });
    }

    private void fadeOutAnimation () {

        if (this.isFadeOut)
            return;

        this.isFadeIn = true;
        this.isFadeOut = true;

        this.m_AnimeTw = m_Img.DOAnchorPosX (-150f, 1f)
            .SetEase (Ease.Linear)
            .OnComplete (() => {
                this.isFadeIn = false;
            })
            .OnKill (() => {

            });
    }

実行してみると、アニメーション中に別のアニメーションが割り込まなくなりました。