Springs
Springs follow the value of other state objects using a physical spring simulation. This can be used for 'springy' effects, or for smoothing out movement naturally without abrupt changes in direction.
Usage¶
To create a new spring object, call scope:Spring()
and pass it a state object
to move towards:
local goal = scope:Value(0)
local animated = scope:Spring(goal)
The spring will smoothly follow the 'goal' state object over time.
As with other state objects, you can peek()
at its value at any time:
print(peek(animated)) --> 0.26425...
To configure how the spring moves, you can provide a speed and damping ratio to use. Both are optional, and both can be state objects if desired:
local goal = scope:Value(0)
local speed = 25
local damping = scope:Value(0.5)
local animated = scope:Spring(goal, speed, damping)
You can also set the position and velocity of the spring at any time.
animated:setPosition(5) -- teleport the spring to 5
animated:setVelocity(2) -- from here, move 2 units/second
You can use many different kinds of values with springs, not just numbers. Vectors, CFrames, Color3s, UDim2s and other number-based types are supported; each number inside the type is animated individually.
local goalPosition = scope:Value(UDim2.new(0.5, 0, 0, 0))
local animated = scope:Spring(goalPosition, 25, 0.5)
Damping Ratio¶
The damping ratio (a.k.a damping) of the spring changes the friction in the physics simulation. Lower values allow the spring to move freely and oscillate up and down, while higher values restrict movement.
Zero damping¶
Zero damping means no friction is applied, so the spring will oscillate forever without losing energy. This is generally not useful.
Underdamping¶
A damping between 0 and 1 means some friction is applied. The spring will still oscillate, but it will lose energy and eventually settle at the goal.
Critical damping¶
A damping of exactly 1 means just enough friction is applied to stop the spring from oscillating. It reaches its goal as quickly as possible without going past.
This is also commonly known as critical damping.
Overdamping¶
A damping above 1 applies excessive friction to the spring. The spring behaves like it's moving through honey, glue or some other viscous fluid.
Overdamping reduces the effect of velocity changes, and makes movement more rigid.
Speed¶
The speed of the spring scales how much time it takes for the spring to move. Doubling the speed makes it move twice as fast; halving the speed makes it move twice as slow.
Interruption¶
Springs do not share the same interruption problems as tweens. When the goal changes, springs are guaranteed to preserve both position and velocity, reducing jank:
This also means springs are suitable for following rapidly changing values: