Lerp
Example
Example of simple Lerp usage for animations.
Example
Advanced example of Lerp animation: A health bar that will smooth the health change over 0.5 seconds to reach new health value from the previous value.
local start, oldhp, newhp = 0, -1, -1
local barW = 200
local animationTime = 0.5 -- seconds
hook.Add( "HUDPaint", "LerpAnimation", function()
-- Local player still loading, do nothing
if ( !IsValid( LocalPlayer() ) ) then return end
local hp = LocalPlayer():Health()
local maxhp = LocalPlayer():GetMaxHealth()
-- The values are not initialized yet, do so right now
if ( oldhp == -1 and newhp == -1 ) then
oldhp = hp
newhp = hp
end
-- You can use a different smoothing function here
local smoothHP = Lerp( ( SysTime() - start ) / animationTime, oldhp, newhp )
-- Health was changed, initialize the animation
if newhp ~= hp then
-- Old animation is still in progress, adjust
if ( smoothHP ~= hp ) then
-- Pretend our current "smooth" position was the target so the animation will
-- not jump to the old target and start to the new target from there
newhp = smoothHP
end
oldhp = newhp
start = SysTime()
newhp = hp
end
draw.RoundedBox( 4, 100, 200, barW, 100, color_black )
draw.RoundedBox( 4, 100, 200, math.max( 0, smoothHP ) / maxhp * barW, 100, color_white )
end )