Garry's Mod Wiki

Lerp

number Lerp( number t, number from, number to )

Description

Performs a linear interpolation from the start number to the end number.

This function provides a very efficient and easy way to smooth out movements.

This function is not meant to be used with constant value in the first argument, if you're dealing with animation! Use a value that changes over time. See example for proper usage of Lerp for animations

Arguments

1 number t
The fraction for finding the result. This number is clamped between 0 and 1. Shouldn't be a constant.
2 number from
The starting number. The result will be equal to this if delta is 0.
3 number to
The ending number. The result will be equal to this if delta is 1.

Returns

1 number
The result of the linear interpolation, (1 - t) * from + t * to.

Example

Example of simple Lerp usage for animations.

local start = SysTime() hook.Add("HUDPaint", "LerpAnimation", function() draw.RoundedBox( 4, 100, 100, Lerp( SysTime() - start, 0, 100 ), 20, color_white ) if SysTime() - start > 2 then start = SysTime() end end)

Example

Advanced example of Lerp animation. Try to improve this code: If the animation is completed, start a new animation from where it stopped, not from oldhp of the previous animation.

local start, oldhp, newhp = 0, 0, 0 hook.Add("HUDPaint", "LerpAnimation", function() local hp = LocalPlayer():Health() if newhp ~= hp then start = SysTime() newhp = hp elseif SysTime() - start > 0.5 then oldhp = hp end draw.RoundedBox( 4, 100, 200, 200, 100, color_black ) draw.RoundedBox( 4, 100, 200, math.max(0, Lerp( (SysTime() - start) / 0.5, oldhp, newhp) ) / LocalPlayer():GetMaxHealth() * 200, 100, color_white ) end)

Page Links


Special Pages


Wikis

?

Render Time: 38ms

DB GetPage 2
Generate Html 12
SaveChanges (1) 15
Render Body 0
Render Sidebar 5