Skip to content

Instantly share code, notes, and snippets.

@TheAllenChou
Last active August 26, 2019 10:15
Show Gist options
  • Save TheAllenChou/9418f1e0145b3e4b09ffbd65396c342d to your computer and use it in GitHub Desktop.
Save TheAllenChou/9418f1e0145b3e4b09ffbd65396c342d to your computer and use it in GitHub Desktop.
Value Seeking
// 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