Garry's Mod Wiki

Revision Difference

Global.Lerp#526731

<function name="Lerp" parent="Global" type="libraryfunc"> <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. <note>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</note> </description> <realm>Shared and Menu</realm> <file line="236-L243">lua/includes/util.lua</file> <args> <arg name="t" type="number">The fraction for finding the result. This number is clamped between 0 and 1. Shouldn't be a constant.</arg> <arg name="from" type="number">The starting number. The result will be equal to this if delta is 0.</arg> <arg name="to" type="number">The ending number. The result will be equal to this if delta is 1.</arg> </args> <rets> <ret name="" type="number">The result of the linear interpolation, `(1 - t) * from + t * to`.</ret> </rets> </function> <example> <description>Example of basic Lerp usage for animations. Here counting up some dollars. Increase the time to make it count faster.</description>⤶ ⤶ <code>⤶ local myMoney = 0⤶ hook.Add("HUDPaint", "LerpAnimation", function()⤶ myMoney = Lerp(0.002, myMoney, 1000000)⤶ local moneyText = "My money is this much now: $"..math.Round(myMoney)⤶ ⤶ draw.DrawText(⤶ moneyText,⤶ "DermaDefault",⤶ 20,⤶ ScrH() - 200,⤶ Color(255,255,255,255),⤶ TEXT_ALIGN_LEFT⤶ )⤶ end)⤶ </code>⤶ </example>⤶ ⤶ <example>⤶ <description>Example of simple Lerp usage for animations.</description> <code> 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) </code> </example> <example> <description>Advanced example of Lerp animation. Try to improve this code: If the animation is completed yet start newe animation from where it stops, not from `oldhp` of previous animation.</description> <code> 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) </code> </example>