9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

なめらかに方向転換 ~もとい、Easing

Last updated at Posted at 2016-06-05

あるオブジェクトの
transformのrotationを変更することで
向きは変えることができる

rotationは四元数なので
四元数のクラスである
Quaternionの補完を使うことができる

今向いている向きから
特定の向きへ
向きをなめらかに変えたい場合

現在のrotationと
向きたい向きのオブジェクトのrotationとを
Slerpで補完することができる


    void TurnAround(Transform target, int count)
    {
        StartCoroutine(TurnAroundCore(target, count));
    }

    IEnumerator TurnAroundCore(Transform target, int count)
    {
        var from = transform.rotation;
        var to   = target.transform.rotation;

        var quaternions = Enumerable.Range(1, count)
            .Select(i => (float)i / (float)count)
            .Select(f => Quaternion.Slerp(from, to, f));

        foreach (var quaternion in quaternions)
        {
            transform.rotation = quaternion;
            yield return new WaitForEndOfFrame();
        }
    }

これだと向きの振り方が
素直すぎるので
補完関数をかましてみる


    void TurnAround(Transform target, int count)
    {
        Func<float, float> curve = (v) =>
        {
            var rad = v * Mathf.PI / 2f;
            var sin = Mathf.Sin(rad);
            return sin;
        };

        StartCoroutine(TurnAroundCore(target, count, curve));
    }

    IEnumerator TurnAroundCore(Transform target, int count, Func<float, float> curve)
    {
        var from = transform.rotation;
        var to   = target.transform.rotation;

        var quaternions = Enumerable.Range(1, count)
            .Select(i => (float)i / (float)count)
            .Select(curve)
            .Select(f => Quaternion.Slerp(from, to, f));

        foreach (var quaternion in quaternions)
        {
            transform.rotation = quaternion;
            yield return new WaitForEndOfFrame();
        }
    }

補完といえば、Robert Pennerさんのeasingですね。
http://robertpenner.com/easing/

ところがUnity的には肝心のC#のコードがリンク切れ。
と思ったら、acron0さんがgithubに補完関数を上げてくれていた。
https://github.com/acron0/Easings/blob/master/Easings.cs

acron0さんのは関数が正規化してあるので、上のTurnAroundCore関数の引数curveにそのまま渡すことができる。

Func<float, float> curve = Easings.BounceEaseOut;
StartCoroutine(TurnAroundCore(target, count, curve));

acron0さんの補完関数を使う前の、いわゆるLinerの状態だとコレ
20160607_021504.gif

たとえば BounceEaseOut を使うとこうなる。
20160607_022412.gif

あれっanimationGifだめなん?

9
9
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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?