Created
April 15, 2018 10:23
-
-
Save stakira/1ac34b257e219c1f5c36376b9d7fba5a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Gradually changes a value towards a desired goal over time. | |
public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, [uei.DefaultValue("Mathf.Infinity")] float maxSpeed, [uei.DefaultValue("Time.deltaTime")] float deltaTime) | |
{ | |
// Based on Game Programming Gems 4 Chapter 1.10 | |
smoothTime = Mathf.Max(0.0001F, smoothTime); | |
float omega = 2F / smoothTime; | |
float x = omega * deltaTime; | |
float exp = 1F / (1F + x + 0.48F * x * x + 0.235F * x * x * x); | |
float change = current - target; | |
float originalTo = target; | |
// Clamp maximum speed | |
float maxChange = maxSpeed * smoothTime; | |
change = Mathf.Clamp(change, -maxChange, maxChange); | |
target = current - change; | |
float temp = (currentVelocity + omega * change) * deltaTime; | |
currentVelocity = (currentVelocity - omega * temp) * exp; | |
float output = target + (change + temp) * exp; | |
// Prevent overshooting | |
if (originalTo - current > 0.0F == output > originalTo) | |
{ | |
output = originalTo; | |
currentVelocity = (output - originalTo) / deltaTime; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment