/* The MIT License (MIT) Copyright (c) 2016 Digital Ruby, LLC http://www.digitalruby.com Created by Jeff Johnson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if UNITY || UNITY_2017_4_OR_NEWER #define IS_UNITY #endif using System; using System.Collections.Generic; using UnityEngine; namespace DigitalRuby.Tween { /// /// State of an ITween object /// public enum TweenState { /// /// The tween is running. /// Running, /// /// The tween is paused. /// Paused, /// /// The tween is stopped. /// Stopped } /// /// The behavior to use when manually stopping a tween. /// public enum TweenStopBehavior { /// /// Does not change the current value. /// DoNotModify, /// /// Causes the tween to progress to the end value immediately. /// Complete } #if IS_UNITY /// /// Tween manager - do not add directly as a script, instead call the static methods in your other scripts. /// public class TweenFactory : MonoBehaviour { private static GameObject root; private static readonly List tweens = new List(); private static GameObject toDestroy; private static void EnsureCreated() { if (root == null && Application.isPlaying) { root = GameObject.Find("DigitalRubyTween"); if (root == null || root.GetComponent() == null) { if (root != null) { toDestroy = root; } root = new GameObject { name = "DigitalRubyTween", hideFlags = HideFlags.HideAndDontSave }; root.AddComponent().hideFlags = HideFlags.HideAndDontSave; } if (Application.isPlaying) { GameObject.DontDestroyOnLoad(root); } } } private void Start() { UnityEngine.SceneManagement.SceneManager.sceneLoaded += SceneManagerSceneLoaded; if (toDestroy != null) { GameObject.Destroy(toDestroy); toDestroy = null; } } private void SceneManagerSceneLoaded(UnityEngine.SceneManagement.Scene s, UnityEngine.SceneManagement.LoadSceneMode m) { if (ClearTweensOnLevelLoad) { tweens.Clear(); } } private void Update() { ITween t; for (int i = tweens.Count - 1; i >= 0; i--) { t = tweens[i]; if (t.Update(t.TimeFunc()) && i < tweens.Count && tweens[i] == t) { tweens.RemoveAt(i); } } } /// /// Start and add a float tween /// /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// FloatTween public static FloatTween Tween(object key, float start, float end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { FloatTween t = new FloatTween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Start and add a Vector2 tween /// /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector2Tween public static Vector2Tween Tween(object key, Vector2 start, Vector2 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector2Tween t = new Vector2Tween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Start and add a Vector3 tween /// /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector3Tween public static Vector3Tween Tween(object key, Vector3 start, Vector3 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector3Tween t = new Vector3Tween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Start and add a Vector4 tween /// /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector4Tween public static Vector4Tween Tween(object key, Vector4 start, Vector4 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector4Tween t = new Vector4Tween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Start and add a Color tween /// /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// ColorTween public static ColorTween Tween(object key, Color start, Color end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { ColorTween t = new ColorTween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Start and add a Quaternion tween /// /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// QuaternionTween public static QuaternionTween Tween(object key, Quaternion start, Quaternion end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { QuaternionTween t = new QuaternionTween(); t.Key = key; t.Setup(start, end, duration, scaleFunc, progress, completion); t.Start(); AddTween(t); return t; } /// /// Add a tween /// /// Tween to add public static void AddTween(ITween tween) { EnsureCreated(); if (tween.Key != null) { RemoveTweenKey(tween.Key, AddKeyStopBehavior); } tweens.Add(tween); } /// /// Remove a tween /// /// Tween to remove /// Stop behavior /// True if removed, false if not public static bool RemoveTween(ITween tween, TweenStopBehavior stopBehavior) { tween.Stop(stopBehavior); return tweens.Remove(tween); } /// /// Remove a tween by key /// /// Key to remove /// Stop behavior /// True if removed, false if not public static bool RemoveTweenKey(object key, TweenStopBehavior stopBehavior) { if (key == null) { return false; } bool foundOne = false; for (int i = tweens.Count - 1; i >= 0; i--) { ITween t = tweens[i]; if (key.Equals(t.Key)) { t.Stop(stopBehavior); tweens.RemoveAt(i); foundOne = true; } } return foundOne; } /// /// Clear all tweens /// public static void Clear() { tweens.Clear(); } /// /// Stop behavior if you add a tween with a key and tweens already exist with the key /// public static TweenStopBehavior AddKeyStopBehavior = TweenStopBehavior.DoNotModify; /// /// Whether to clear tweens on level load, default is false /// public static bool ClearTweensOnLevelLoad { get; set; } /// /// Default time func /// public static Func DefaultTimeFunc = TimeFuncDeltaTime; /// /// Time func delta time instance /// public static readonly Func TimeFuncDeltaTimeFunc = TimeFuncDeltaTime; /// /// Time func unscaled delta time instance /// public static readonly Func TimeFuncUnscaledDeltaTimeFunc = TimeFuncUnscaledDeltaTime; /// /// Time func that uses Time.deltaTime /// /// Time.deltaTime private static float TimeFuncDeltaTime() { return Time.deltaTime; } /// /// Time func that uses Time.unscaledDeltaTime /// /// Time.unscaledDeltaTime private static float TimeFuncUnscaledDeltaTime() { return Time.unscaledDeltaTime; } } /// /// Extensions for tween for game objects - unity only /// public static class GameObjectTweenExtensions { /// /// Start and add a float tween /// /// Game object /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// FloatTween public static FloatTween Tween(this GameObject obj, object key, float start, float end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { FloatTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } /// /// Start and add a Vector2 tween /// /// Game object /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector2Tween public static Vector2Tween Tween(this GameObject obj, object key, Vector2 start, Vector2 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector2Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } /// /// Start and add a Vector3 tween /// /// Game object /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector3Tween public static Vector3Tween Tween(this GameObject obj, object key, Vector3 start, Vector3 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector3Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } /// /// Start and add a Vector4 tween /// /// Game object /// Key /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// Vector4Tween public static Vector4Tween Tween(this GameObject obj, object key, Vector4 start, Vector4 end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { Vector4Tween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } /// /// Start and add a Color tween /// /// Game object /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// ColorTween public static ColorTween Tween(this GameObject obj, object key, Color start, Color end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { ColorTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } /// /// Start and add a Quaternion tween /// /// Game object /// Start value /// End value /// Duration in seconds /// Scale function /// Progress handler /// Completion handler /// QuaternionTween public static QuaternionTween Tween(this GameObject obj, object key, Quaternion start, Quaternion end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { QuaternionTween t = TweenFactory.Tween(key, start, end, duration, scaleFunc, progress, completion); t.GameObject = obj; t.Renderer = obj.GetComponent(); return t; } } #endif /// /// Interface for a tween object. /// public interface ITween { /// /// The key that identifies this tween - can be null /// object Key { get; } /// /// Gets the current state of the tween. /// TweenState State { get; } /// /// Time function /// System.Func TimeFunc { get; set; } /// /// Start the tween. /// void Start(); /// /// Pauses the tween. /// void Pause(); /// /// Resumes the paused tween. /// void Resume(); /// /// Stops the tween. /// /// The behavior to use to handle the stop. void Stop(TweenStopBehavior stopBehavior); /// /// Updates the tween. /// /// The elapsed time to add to the tween. /// True if done, false if not bool Update(float elapsedTime); } /// /// Interface for a tween object that handles a specific type. /// /// The type to tween. public interface ITween : ITween where T : struct { /// /// Gets the current value of the tween. /// T CurrentValue { get; } /// /// Gets the current progress of the tween. /// float CurrentProgress { get; } /// /// Initialize a tween. /// /// The start value. /// The end value. /// The duration of the tween. /// A function used to scale progress over time. /// Progress callback /// Called when the tween completes Tween Setup(T start, T end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null); } /// /// An implementation of a tween object. /// /// The type to tween. public class Tween : ITween where T : struct { private readonly Func, T, T, float, T> lerpFunc; private float currentTime; private float duration; private Func scaleFunc; private System.Action> progressCallback; private System.Action> completionCallback; private TweenState state; private T start; private T end; private T value; private ITween continueWith; /// /// The key that identifies this tween - can be null /// public object Key { get; set; } /// /// Gets the current time of the tween. /// public float CurrentTime { get { return currentTime; } } /// /// Gets the duration of the tween. /// public float Duration { get { return duration; } } /// /// Delay before starting the tween /// public float Delay { get; set; } /// /// Gets the current state of the tween. /// public TweenState State { get { return state; } } /// /// Gets the starting value of the tween. /// public T StartValue { get { return start; } } /// /// Gets the ending value of the tween. /// public T EndValue { get { return end; } } /// /// Gets the current value of the tween. /// public T CurrentValue { get { return value; } } /// /// Time function - returns elapsed time for next frame /// public System.Func TimeFunc { get; set; } #if IS_UNITY /// /// The game object - null if none /// public GameObject GameObject { get; set; } /// /// The renderer - null if none /// public Renderer Renderer { get; set; } /// /// Whether to force update even if renderer is null or not visible or deactivated, default is false /// public bool ForceUpdate { get; set; } #endif /// /// Gets the current progress of the tween (0 - 1). /// public float CurrentProgress { get; private set; } /// /// Initializes a new Tween with a given lerp function. /// /// /// C# generics are good but not good enough. We need a delegate to know how to /// interpolate between the start and end values for the given type. /// /// The interpolation function for the tween type. public Tween(Func, T, T, float, T> lerpFunc) { this.lerpFunc = lerpFunc; state = TweenState.Stopped; #if IS_UNITY TimeFunc = TweenFactory.DefaultTimeFunc; #else // TODO: Implement your own time functions #endif } /// /// Initialize a tween. /// /// The start value. /// The end value. /// The duration of the tween. /// A function used to scale progress over time. /// Progress callback /// Called when the tween completes public Tween Setup(T start, T end, float duration, Func scaleFunc, System.Action> progress, System.Action> completion = null) { scaleFunc = (scaleFunc ?? TweenScaleFunctions.Linear); currentTime = 0; this.duration = duration; this.scaleFunc = scaleFunc; this.progressCallback = progress; this.completionCallback = completion; this.start = start; this.end = end; return this; } /// /// Starts a tween. Setup must be called first. /// public void Start() { if (state != TweenState.Running) { if (duration <= 0.0f && Delay <= 0.0f) { // complete immediately value = end; if (progressCallback != null) { progressCallback(this); } if (completionCallback != null) { completionCallback(this); } return; } state = TweenState.Running; UpdateValue(); } } /// /// Pauses the tween. /// public void Pause() { if (state == TweenState.Running) { state = TweenState.Paused; } } /// /// Resumes the paused tween. /// public void Resume() { if (state == TweenState.Paused) { state = TweenState.Running; } } /// /// Stops the tween. /// /// The behavior to use to handle the stop. public void Stop(TweenStopBehavior stopBehavior) { if (state != TweenState.Stopped) { state = TweenState.Stopped; if (stopBehavior == TweenStopBehavior.Complete) { currentTime = duration; UpdateValue(); if (completionCallback != null) { completionCallback.Invoke(this); completionCallback = null; } if (continueWith != null) { continueWith.Start(); #if IS_UNITY TweenFactory.AddTween(continueWith); #else // TODO: Implement your own continueWith handling #endif continueWith = null; } } } } /// /// Updates the tween. /// /// The elapsed time to add to the tween. /// True if done, false if not public bool Update(float elapsedTime) { if (state == TweenState.Running) { if (Delay > 0.0f) { currentTime += elapsedTime; if (currentTime <= Delay) { // delay is not over yet return false; } else { // set to left-over time beyond delay currentTime = (currentTime - Delay); Delay = 0.0f; } } else { currentTime += elapsedTime; } if (currentTime >= duration) { Stop(TweenStopBehavior.Complete); return true; } else { UpdateValue(); return false; } } return (state == TweenState.Stopped); } /// /// Set another tween to execute when this tween finishes. Inherits the Key and if using Unity, GameObject, Renderer and ForceUpdate properties. /// /// Type of new tween /// New tween /// New tween public Tween ContinueWith(Tween tween) where TNewTween : struct { tween.Key = Key; #if IS_UNITY tween.GameObject = GameObject; tween.Renderer = Renderer; tween.ForceUpdate = ForceUpdate; #endif continueWith = tween; return tween; } /// /// Helper that uses the current time, duration, and delegates to update the current value. /// private void UpdateValue() { #if IS_UNITY if (Renderer == null || Renderer.isVisible || ForceUpdate) { #endif CurrentProgress = scaleFunc(currentTime / duration); value = lerpFunc(this, start, end, CurrentProgress); if (progressCallback != null) { progressCallback.Invoke(this); } #if IS_UNITY } #endif } } /// /// Object used to tween float values. /// public class FloatTween : Tween { private static float LerpFloat(ITween t, float start, float end, float progress) { return start + (end - start) * progress; } private static readonly Func, float, float, float, float> LerpFunc = LerpFloat; /// /// Initializes a new FloatTween instance. /// public FloatTween() : base(LerpFunc) { } } /// /// Object used to tween Vector2 values. /// public class Vector2Tween : Tween { private static Vector2 LerpVector2(ITween t, Vector2 start, Vector2 end, float progress) { return Vector2.Lerp(start, end, progress); } private static readonly Func, Vector2, Vector2, float, Vector2> LerpFunc = LerpVector2; /// /// Initializes a new Vector2Tween instance. /// public Vector2Tween() : base(LerpFunc) { } } /// /// Object used to tween Vector3 values. /// public class Vector3Tween : Tween { private static Vector3 LerpVector3(ITween t, Vector3 start, Vector3 end, float progress) { return Vector3.Lerp(start, end, progress); } private static readonly Func, Vector3, Vector3, float, Vector3> LerpFunc = LerpVector3; /// /// Initializes a new Vector3Tween instance. /// public Vector3Tween() : base(LerpFunc) { } } /// /// Object used to tween Vector4 values. /// public class Vector4Tween : Tween { private static Vector4 LerpVector4(ITween t, Vector4 start, Vector4 end, float progress) { return Vector4.Lerp(start, end, progress); } private static readonly Func, Vector4, Vector4, float, Vector4> LerpFunc = LerpVector4; /// /// Initializes a new Vector4Tween instance. /// public Vector4Tween() : base(LerpFunc) { } } /// /// Object used to tween Color values. /// public class ColorTween : Tween { private static Color LerpColor(ITween t, Color start, Color end, float progress) { return Color.Lerp(start, end, progress); } private static readonly Func, Color, Color, float, Color> LerpFunc = LerpColor; /// /// Initializes a new ColorTween instance. /// public ColorTween() : base(LerpFunc) { } } /// /// Object used to tween Quaternion values. /// public class QuaternionTween : Tween { private static Quaternion LerpQuaternion(ITween t, Quaternion start, Quaternion end, float progress) { return Quaternion.Lerp(start, end, progress); } private static readonly Func, Quaternion, Quaternion, float, Quaternion> LerpFunc = LerpQuaternion; /// /// Initializes a new QuaternionTween instance. /// public QuaternionTween() : base(LerpFunc) { } } /// /// Tween scale functions /// Implementations based on http://theinstructionlimit.com/flash-style-tweeneasing-functions-in-c, which are based on http://www.robertpenner.com/easing/ /// public static class TweenScaleFunctions { private const float halfPi = Mathf.PI * 0.5f; /// /// A linear progress scale function. /// public static readonly Func Linear = LinearFunc; private static float LinearFunc(float progress) { return progress; } /// /// A quadratic (x^2) progress scale function that eases in. /// public static readonly Func QuadraticEaseIn = QuadraticEaseInFunc; private static float QuadraticEaseInFunc(float progress) { return EaseInPower(progress, 2); } /// /// A quadratic (x^2) progress scale function that eases out. /// public static readonly Func QuadraticEaseOut = QuadraticEaseOutFunc; private static float QuadraticEaseOutFunc(float progress) { return EaseOutPower(progress, 2); } /// /// A quadratic (x^2) progress scale function that eases in and out. /// public static readonly Func QuadraticEaseInOut = QuadraticEaseInOutFunc; private static float QuadraticEaseInOutFunc(float progress) { return EaseInOutPower(progress, 2); } /// /// A cubic (x^3) progress scale function that eases in. /// public static readonly Func CubicEaseIn = CubicEaseInFunc; private static float CubicEaseInFunc(float progress) { return EaseInPower(progress, 3); } /// /// A cubic (x^3) progress scale function that eases out. /// public static readonly Func CubicEaseOut = CubicEaseOutFunc; private static float CubicEaseOutFunc(float progress) { return EaseOutPower(progress, 3); } /// /// A cubic (x^3) progress scale function that eases in and out. /// public static readonly Func CubicEaseInOut = CubicEaseInOutFunc; private static float CubicEaseInOutFunc(float progress) { return EaseInOutPower(progress, 3); } /// /// A quartic (x^4) progress scale function that eases in. /// public static readonly Func QuarticEaseIn = QuarticEaseInFunc; private static float QuarticEaseInFunc(float progress) { return EaseInPower(progress, 4); } /// /// A quartic (x^4) progress scale function that eases out. /// public static readonly Func QuarticEaseOut = QuarticEaseOutFunc; private static float QuarticEaseOutFunc(float progress) { return EaseOutPower(progress, 4); } /// /// A quartic (x^4) progress scale function that eases in and out. /// public static readonly Func QuarticEaseInOut = QuarticEaseInOutFunc; private static float QuarticEaseInOutFunc(float progress) { return EaseInOutPower(progress, 4); } /// /// A quintic (x^5) progress scale function that eases in. /// public static readonly Func QuinticEaseIn = QuinticEaseInFunc; private static float QuinticEaseInFunc(float progress) { return EaseInPower(progress, 5); } /// /// A quintic (x^5) progress scale function that eases out. /// public static readonly Func QuinticEaseOut = QuinticEaseOutFunc; private static float QuinticEaseOutFunc(float progress) { return EaseOutPower(progress, 5); } /// /// A quintic (x^5) progress scale function that eases in and out. /// public static readonly Func QuinticEaseInOut = QuinticEaseInOutFunc; private static float QuinticEaseInOutFunc(float progress) { return EaseInOutPower(progress, 5); } /// /// A sine progress scale function that eases in. /// public static readonly Func SineEaseIn = SineEaseInFunc; private static float SineEaseInFunc(float progress) { return Mathf.Sin(progress * halfPi - halfPi) + 1; } /// /// A sine progress scale function that eases out. /// public static readonly Func SineEaseOut = SineEaseOutFunc; private static float SineEaseOutFunc(float progress) { return Mathf.Sin(progress * halfPi); } /// /// A sine progress scale function that eases in and out. /// public static readonly Func SineEaseInOut = SineEaseInOutFunc; private static float SineEaseInOutFunc(float progress) { return (Mathf.Sin(progress * Mathf.PI - halfPi) + 1) / 2; } private static float EaseInPower(float progress, int power) { return Mathf.Pow(progress, power); } private static float EaseOutPower(float progress, int power) { int sign = power % 2 == 0 ? -1 : 1; return (sign * (Mathf.Pow(progress - 1, power) + sign)); } private static float EaseInOutPower(float progress, int power) { progress *= 2.0f; if (progress < 1) { return Mathf.Pow(progress, power) / 2.0f; } else { int sign = power % 2 == 0 ? -1 : 1; return (sign / 2.0f * (Mathf.Pow(progress - 2, power) + sign * 2)); } } } }