Search code examples
floating-pointtarget

Moving a float towards another float by a specified amount


I have a current value that i want to move towards a target by an amount. If the value overshoots the target I want it to clamp.

A standard use for this function would be moving an object towards a destination every frame in pretty much any game engine.

I have my own implementation below, but was wondering if there was something cleaner.

public static float MoveTowards(float orig, float target, float amount)
{
    //moves orig towards target by amount. Clamps to target if overshot.
    float result = orig;
    if (orig < target) {
        result = orig+amount;
        if (result > target) {
            result = target;
        }
    } else if (orig > target) {
        result = orig - amount;
        if (result < target) {
            result = target;
        }
    } else {
        result = target;
    }
    return result;

}       

Answers in any language are fine, though hopefully something like java/C#/python etc.


Solution

  • if (orig < target)
        result = min(orig+amount, target)
    else if (orig > target)
        result = max(orig-amount, target)
    else
        result = target