LoginSignup
10
4

More than 5 years have passed since last update.

[Unity] DOTweenで相対的に値を増減させたい時には .SetRelative() を使う

Last updated at Posted at 2018-12-04

開発環境

  • Unity 2018.2.16f1
  • DOTweenPro 1.0.075 (ProでなくてOK)

概要

DOTweenで現在の値を元に相対量を増減させるということをする際に、まず思いつくのは以下のような 「現在の値に対して相対量を加減した値を終了値として渡す」 というコードです。

DOTweenMoveFrom.cs
using System;
using DG.Tweening;
using UnityEngine;
using UniRx;

public class DOTweenMoveFrom : MonoBehaviour
{
    void Start()
    {
        // UniRx: 2秒ごとに処理を実行する
        Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(_ => this.Move());
    }

    private void Move()
    {
        var position = this.transform.position + Vector3.right;
        this.transform.DOMove(position, 1f);
    }
}

実はもう少し楽に記載する方法があり、それが Tween.SetRelative() です。Tweenに対してメソッドチェインで呼び出すことで、Tweenで指定した値を相対値として取り扱ってくれます。下記の例題だと、一定時間毎に Vector3.right だけ移動します (最初の例と同一の挙動)

DOTweenMoveFrom.cs
using System;
using DG.Tweening;
using UnityEngine;
using UniRx;

public class DOTweenMoveFrom : MonoBehaviour
{
    void Start()
    {
        Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(_ => this.Move());
    }

    private void Move()
    {
        this.transform.DOMove(Vector3.right, 1f).SetRelative();
    }
}

setrelative.gif

この Tween.SetRelative() は値を操作する系統のTweenであれば、基本的に何でも使えます。試しに「右に移動する」「回転する」「フェードアウトする」の3通りの挙動に対して適応します。

DOTweenMoveFrom.cs
using System;
using DG.Tweening;
using UnityEngine;
using UniRx;

public class DOTweenMoveFrom : MonoBehaviour
{
    void Start()
    {
        Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(_ => this.Move());
    }

    private void Move()
    {
        this.transform.DOMove(Vector3.right, 1f).SetRelative();
        this.transform.DOLocalRotate(new Vector3(0, 0, 90), 1f).SetRelative();
        this.GetComponent<SpriteRenderer>().DOFade(-0.2f, 1f).SetRelative();
    }
}

setrelative2.gif

また上記と同等の挙動は Sequence を利用して、以下のように記載することもできます。

DOTween.Sequence()
    .Append(this.transform.DOMove(Vector3.right, 1f))
    .Join(this.transform.DOLocalRotate(new Vector3(0, 0, 90), 1f))
    .Join(this.GetComponent<SpriteRenderer>().DOFade(-0.2f, 1f))
    .SetRelative();
10
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4