Skip to content

Instantly share code, notes, and snippets.

@brihernandez
Last active January 10, 2024 08:05
Show Gist options
  • Save brihernandez/dd43a053180ac1c98d6070c31eaa8b8e to your computer and use it in GitHub Desktop.
Save brihernandez/dd43a053180ac1c98d6070c31eaa8b8e to your computer and use it in GitHub Desktop.
Framerate independent damping
using UnityEngine;
// Thanks to Rory Driscoll
// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
public static class SmoothDamp
{
/// <summary>
/// Creates dampened motion between a and b that is framerate independent.
/// </summary>
/// <param name="from">Initial parameter</param>
/// <param name="to">Target parameter</param>
/// <param name="speed">Smoothing factor</param>
/// <param name="dt">Time since last damp call</param>
/// <returns></returns>
static public Quaternion Rotate(Quaternion from, Quaternion to, float speed, float dt)
{
return Quaternion.Slerp(from, to, 1 - Mathf.Exp(-speed * dt));
}
/// <summary>
/// Creates dampened motion between a and b that is framerate independent.
/// </summary>
/// <param name="from">Initial parameter</param>
/// <param name="to">Target parameter</param>
/// <param name="speed">Smoothing factor</param>
/// <param name="dt">Time since last damp call</param>
/// <returns></returns>
static public Vector3 Move(Vector3 from, Vector3 to, float speed, float dt)
{
return Vector3.Lerp(from, to, 1 - Mathf.Exp(-speed * dt));
}
/// <summary>
/// Creates dampened motion between a and b that is framerate independent.
/// </summary>
/// <param name="from">Initial parameter</param>
/// <param name="to">Target parameter</param>
/// <param name="speed">Smoothing factor</param>
/// <param name="dt">Time since last damp call</param>
/// <returns></returns>
static public Vector2 Move(Vector2 from, Vector2 to, float speed, float dt)
{
return Vector2.Lerp(from, to, 1 - Mathf.Exp(-speed * dt));
}
/// <summary>
/// Creates dampened motion between a and b that is framerate independent.
/// </summary>
/// <param name="from">Initial parameter</param>
/// <param name="to">Target parameter</param>
/// <param name="speed">Smoothing factor</param>
/// <param name="dt">Time since last damp call</param>
/// <returns></returns>
static public float Move(float from, float to, float speed, float dt)
{
return Mathf.Lerp(from, to, 1 - Mathf.Exp(-speed * dt));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment