Imagine you wanted to do a regular tween between two values. You can use :GetValue like so:
local start = 0 --start
local goal = 5 --goal
local tweenInfo = TweenInfo.new(2, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
local value = 0
local elapsed = 0
local cnStepped
local function onStepped(t, dt)
elapsed = math.min(elapsed + dt, tweenInfo.Time)
local alpha = game:GetService('TweenService'):GetValue(elapsed / tweenInfo.Time, tweenInfo.EasingStyle, tweenInfo.EasingDirection)
value = start + (goal - start) * alpha --you might recongize this: it's the equation for a lerp
print(value)
if elapsed >= tweenInfo.Time then
cnStepped:Disconnect()
end
end
cnStepped = game:GetService('RunService').Stepped:Connect(onStepped)
Now, to explain this. :GetValue is a method that returns a number from 0-1 given a number from 0-1. All the easing styles and easing directions have different curves, but all these curves go from 0-1 no matter what. For example, if you have a linear easingstyle, and you give it 0.3, it will return 0.3. However, if you use a quadratic easingstyle, it will apply a quadratic curve to the value which means it’ll still be from a range of 0-1, but it’ll modify the value. In this case, it’ll be 0.18.
When you want to move a value from a start goal to an end goal, you interpolate it. Interpolation comes in many forms, but often you here the word “Lerp” which means linear interpolation. As the name suggests, its perfectly linear. However, tweenservice offers way more than just linear movement. Using a lerp algorithm looks like so: (value = start + (goal - start) * alpha)
. Notice the alpha part: that’s the key. The alpha is a value from 0-1, just like what GetValue
returns. So, if we modify the alpha by plugging it into the GetValue
method we can use any tweenservice curve we want in a lerp function.
(value = start + (goal - start) * ts:GetValue(alpha, Enum.EasingStyle.Quad))
for example. Now its a quadratic interpolation instead of a linear one! Very simple. The code above is exactly what Roblox’s tweenservice:Create system uses. While GetValue
isn’t nessescary usually since you can usually make the curves yourself, it’s quite nice to have sometimes.
The code above, starts a run service loop. Each iteration, it adds dt
to a variable called elapsed
. Elapsed is initialized at 0, and is how many seconds it’s been since the interpolation has start. This is important for the alpha
part of our equation above. It seems weird, since you can have any amount of time, 0-3 seconds, 0-200 seconds, but the alpha has to be 0-1. Well, you can normalize the variable, which means you divide the variable by its maxium value, in this case it is the total length of the interpolation. For example, if we had a length from 0-5 and we were at 2 seconds, it would be 2/5
or 0.4
which means we are 40% of the interpolation finished. This is our alpha value! We can plug this into our lerp equation above and we just replicated tween service behavior.