Last active
June 23, 2021 10:17
-
-
Save jackbrookes/7b1215eef6817656a2a8bb9c4a50539f to your computer and use it in GitHub Desktop.
Unity3D Lerp (Linear Interpolation) Coroutines. Contains methods for creating routines which can be used as coroutines to easy lerp over a time period.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
/// <summary> | |
/// Contains methods for creating routines which can be used as coroutines to easy lerp over a time period. | |
/// | |
/// Example moves an object between two points over 5 seconds: | |
/// | |
/// Vector3 startPoint = transform.position; | |
/// Vector3 endPoint = new Vector3(0f, 10f, 0f); | |
/// | |
/// StartCoroutine( | |
/// LerpEnumerator.OnUpdate( | |
/// (t) => transform.position = Vector3.Lerp(startPoint, endPoint, t), | |
/// 5f | |
/// ) | |
/// ); | |
/// | |
/// </summary> | |
public static class LerpEnumerator | |
{ | |
/// <summary> | |
/// Returns a routine that executes `action` on each frame for `duration` (unity scaled time), passing float value from 0-1 linearly across the time period. | |
/// </summary> | |
/// <param name="action">Action that accepts a float argument (0-1).</param> | |
/// <param name="duration">Duration of the routine.</param> | |
/// <returns></returns> | |
public static IEnumerator OnUpdate(Action<float> action, float duration) | |
{ | |
float startTime = Time.time; | |
float t; | |
while ((t = (Time.time - startTime) / duration) <= 1f) | |
{ | |
action.Invoke(t); | |
yield return null; | |
} | |
action.Invoke(1f); | |
} | |
/// <summary> | |
/// Returns a routine that executes `action` on each frame for `duration` (unity unscaled time), passing float value from 0-1 linearly across the time period. | |
/// </summary> | |
/// <param name="action">Action that accepts a float argument (0-1).</param> | |
/// <param name="duration">Duration of the routine.</param> | |
/// <returns></returns> | |
public static IEnumerator OnUnscaledUpdate(Action<float> action, float duration) | |
{ | |
float startTime = Time.unscaledTime; | |
float t; | |
while ((t = (Time.unscaledTime - startTime) / duration) <= 1f) | |
{ | |
action.Invoke(t); | |
yield return null; | |
} | |
action.Invoke(1f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment