Garry's Mod Wiki

math.Approach

  number math.Approach( number current, number target, number change )

Description

Gradually approaches the target value by the specified amount.

Arguments

1 number current
The value we're currently at.
2 number target
The target value. This function will never overshoot this value.
3 number change
The amount that the current value is allowed to change by to approach the target. (It makes no difference whether this is positive or negative.)

Returns

1 number
New current value, closer to the target than it was previously.

Example

Demonstrates what this function does

print( math.Approach( 0, 5, 1 ) ) -- attempts to increment 0 by 1, 0 + 1 is less than 5 so returns 1 print( math.Approach( 4, 5, 3 ) ) -- attempts to increment 4 by 3, 4 + 3 = 7 is greater than 5 so returns 5
Output:
1 5

Example

Common usage example of this function with a control variable.

local MyNumber = 0 local Target = 0 local LastThink = 0 local ChangeRate = 1 hook.Add( "Think", "math.Approach Example", function() local now = CurTime() local timepassed = now - LastThink LastThink = now MyNumber = math.Approach( MyNumber, Target, ChangeRate * timepassed ) -- Normally, you would use MyNumber in code that appears here. end ) -- The following functions are for example only: function GetMyNumber() return MyNumber end function SetMyNumberTarget( newtarget ) Target = newtarget end function SetMyNumberChangeRate( newrate ) ChangeRate = newrate end