aong152
aong152

Reputation: 153

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.

Upvotes: 0

Views: 693

Answers (3)

user2180748
user2180748

Reputation: 21

 currentValue = Mathf.MoveTowards(currentValue , targetVAlue, speed * Time.deltaTime);

Upvotes: 0

aka.nice
aka.nice

Reputation: 9572

You could use min and max as correctly suggested by mdebeus.
But beware: if amount is too small w.r.t. orig magnitude, then orig+amount might == orig and fail to advance.

You might want to call nextafter to mitigate this possible issue, like

result = min( max(orig+amount,nextafter(orig,target)) , target )

Upvotes: 1

mdebeus
mdebeus

Reputation: 1928

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

Upvotes: 1

Related Questions