Last active
February 2, 2025 16:22
-
-
Save TheAllenChou/9418f1e0145b3e4b09ffbd65396c342d to your computer and use it in GitHub Desktop.
Value Seeking
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
// example of how to move a current value towards a target value at a constant speed | |
// without going over the target value | |
// formula is the same for vectors of any dimension | |
Vector3 Seek(Vector3 currentValue, Vector3 targetValue, float maxSpeed, float dt) | |
{ | |
// delta/difference from current value to target value | |
Vector3 delta = targetValue - currentValue; | |
// don't take the square root of magnitude yet | |
// so we can potentially early out on degenerate case of currenvValue ~= targetValue | |
float deltaLenSqr = delta.sqrMagnitude; | |
// just return target value if close enough | |
if (deltaLenSqr < Epsilon /* very small value, say 1e-16f */) | |
return targetValue; | |
// now it's time to do the more expensive square root | |
// and potentially float division later | |
float deltaLen = Mathf.Sqrt(deltaLenSqr); | |
// cap at target value if current step would overshoot | |
float stepLen = maxSpeed * dt; | |
if (stepLen >= deltaLen) | |
return targetValue; | |
// step direction | |
Vector3 deltaDir = delta / deltaLen; | |
// step towards target value | |
return currentValue + deltaDir * stepLen; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment