From 17aca44a3b71e1877c5e684c8164a7284f31d271 Mon Sep 17 00:00:00 2001 From: PrecisionRender Date: Sat, 15 Apr 2023 16:40:03 -0500 Subject: [PATCH] Add `MoveTowards` functions to C++ `Math` --- Source/Engine/Core/Math/Math.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Source/Engine/Core/Math/Math.h b/Source/Engine/Core/Math/Math.h index 162acc97fe..0c9a07841c 100644 --- a/Source/Engine/Core/Math/Math.h +++ b/Source/Engine/Core/Math/Math.h @@ -386,6 +386,36 @@ namespace Math return Min(Min(Min(a, b), c), d); } + /// + /// Moves a value current towards target. + /// + /// The current value. + /// The value to move towards. + /// The maximum change that should be applied to the value. + template + float MoveTowards(const T current, const T target, const T maxDelta) + { + if (Abs(target - current) <= maxDelta) + return target; + return current + Sign(target - current) * maxDelta; + } + + /// + /// Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. + /// + /// + /// + /// + template + float MoveTowardsAngle(const T current, const T target, const T maxDelta) + { + float delta = DeltaAngle(current, target); + if ((-maxDelta < delta) && (delta < maxDelta)) + return target; + target = current + delta; + return MoveTowards(current, target, maxDelta); + } + // Multiply value by itself template static T Square(const T a)