Skip to content

Commit ed1261b

Browse files
committed
RTETools - add exponential decay function
1 parent bc830c3 commit ed1261b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Source/System/RTETools.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,5 +301,35 @@ namespace RTE {
301301
template <typename Type> int Sign(const Type& value) {
302302
return (Type(0) < value) - (Type(0) > value);
303303
}
304+
305+
/// Exponential decay function. Allows decaying a value from A to B at the same rate regardless of delta time. Always stable.
306+
///
307+
/// As an example, assuming variables like this:
308+
/// float current = 1.0f;
309+
/// float target = 0.0f;
310+
/// float decay = 10.0f;
311+
///
312+
/// Then running this:
313+
///
314+
/// current = ExpDecay(current, target, decay, 1.0f / 30.0f);
315+
///
316+
/// Preduces the same result (barring precision errors) as:
317+
///
318+
/// current = ExpDecay(current, target, decay, 1.0f / 60.0f);
319+
/// current = ExpDecay(current, target, decay, 1.0f / 60.0f);
320+
///
321+
/// In both cases, "current" will be equal to about 0.716531310573789.
322+
///
323+
/// Lecture on the topic: https://youtube.com/watch?v=LSNQuFEDOyQ
324+
///
325+
/// @param current The current value that we're decaying.
326+
/// @param target Target we're decaying to.
327+
/// @param decay Rate of decay. For example, with 0.7 the value will be decayed about halfway there in 1 second.
328+
/// @param deltaTime Amount of time of decay to simulate.
329+
/// @returns The decayed value.
330+
inline float ExpDecay(float current, float target, float decay, float deltaTime) {
331+
return target + (current - target) * std::exp(-decay * deltaTime);
332+
}
333+
304334
#pragma endregion
305335
} // namespace RTE

0 commit comments

Comments
 (0)