さけのさかなのブログ

同人ゲーム開発やってます。Unity使ったりする。

イージング処理

 iTweenは便利だけど、ValueToをonupdateで受けて……については流石にアホか!となったので、それならいっそとMonoBehaviourに依存しないイージング処理を書いた。
 コールバックとかはない。Valueを呼んだときにその時の値を計算するだけ。

namespace TSKT
{
    public class EasingValue
    {
        public enum TimeType
        {
            DefaultTime = 0,
            FixedTime = 1,
            RealTime = 2
        }

        float end = 0f;
        float start = 0f;
        float startedTime = 0f;
        float duration = 0f;

        public System.Func<float, float, float, float> EasingFunction { get; set; }

        public TimeType timeType = TimeType.DefaultTime;

        public EasingValue()
        {
            // EasingFunction = イージング関数なにか;
        }

        public float Value
        {
            get
            {
                if (duration == 0f)
                {
                    return end;
                }

                return EasingFunction.Invoke(start, end, NormalizedElapsedTime);
            }
        }

        public float End
        {
            get
            {
                return end;
            }
        }

        public void MoveTo(float value, float duration)
        {
            start = Value;
            end = value;
            this.duration = duration;
            startedTime = Now;
        }

        public void JumpTo(float value)
        {
            start = value;
            end = value;
            duration = 0f;
            startedTime = Now;
        }

        public bool Completed
        {
            get
            {
                if (duration == 0f)
                {
                    return true;
                }
                return NormalizedElapsedTime == 1f;
            }
        }

        float NormalizedElapsedTime
        {
            get
            {
                return Mathf.Clamp01((Now - startedTime) / duration);
            }
        }

        float Now
        {
            get
            {
                switch (timeType)
                {
                    case TimeType.DefaultTime:
                        return Time.time;
                    case TimeType.FixedTime:
                        return Time.fixedTime;
                    case TimeType.RealTime:
                        return Time.realtimeSinceStartup;
                    default:
                        Debug.LogError("wrong time type");
                        return 0f;
                }
            }
        }
    }
}

 イージング関数については、適当にどっかからコピペしてくればいいんじゃなかろうか。それこそiTween.csとか。