Skip to content

Instantly share code, notes, and snippets.

@milend
Last active March 5, 2023 21:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milend/e56762f7bb749cf2a0e2 to your computer and use it in GitHub Desktop.
Save milend/e56762f7bb749cf2a0e2 to your computer and use it in GitHub Desktop.
// https://en.wikipedia.org/wiki/Damping
double HTSpringOverdamped(double time, double damping, double freq, double offset, double velocity) {
NSCParameterAssert(0.0 <= damping);
NSCParameterAssert(damping < 1.0);
if(time <= 0.0)
return offset;
const double wd = freq * (2.0 * M_PI);
const double w0 = wd / sqrt(1.0 - damping * damping);
const double A = offset;
const double B = (1.0 / wd) * (damping * w0 * offset + velocity);
const double expPart = pow(M_E, -damping * w0 * time);
const double sinusoidPart = A * cos(wd * time) + B * sin(wd * time);
return expPart * sinusoidPart;
}
double HTAnimationTimingSpring(double elapsed, double duration, double easePoint, double damping, double freq) {
if(elapsed >= duration)
return 1.0;
static const double HTSpringNormalisedOffset = 1.0;
// distance = distance from equilibrium position (i.e., 0.0)
double startDistance = HTSpringOverdamped(0.0, damping, freq, HTSpringNormalisedOffset, 0.0);
double currentDistance = HTSpringOverdamped(elapsed, damping, freq, HTSpringNormalisedOffset, 0.0);
easePoint = MAX(0.0, MIN(easePoint, 1.0));
double easeTime = easePoint * duration;
if(elapsed > easeTime) {
double easeValue = (elapsed - easeTime) / (duration - easeTime);
currentDistance *= (1.0 - HTAnimationTimingSineEaseInOut(easeValue, 1.0));
}
return 1.0 - (currentDistance / startDistance);
}
double HTAnimationTimingSineEaseInOut(double elapsed, double duration) {
return HTAnimationTimingSineEaseInOutCanonical(elapsed, duration, 0.0, 1.0);
}
// Based on penner equations: http://www.robertpenner.com/easing/
// t: elapsed, d: duration;
// b: base, c: delta;
static double HTAnimationTimingSineEaseInOutCanonical(double t, double d, double b, double c) {
return -c/2.0 * (cos(M_PI*t/d) - 1.0) + b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment