Quick Trick for Tweening Functions [Scripting Tutorial]

TweenService works great to smoothly interpolate properties of instances from a start to a finish, but what if you wanted to do something like make a part smoothly orbit around another? You couldn’t directly use TweenService because it would just connect the start position to the goal position by a straight line and move along it.

The trick to get around this is to use ‘Value’ instances to store a datatype which you are able to Tween, and then connect a function to it’s .Changed event so that you can use the Value as a parameter as it’s being tweened.

Here’s an example where I tweened a NumberValue to be used as the angle for a parameterized orbit to make a star spiral into a black hole :sunglasses::


26e51b44b9908afea130a14589aeefec (directories)

(script)

Source Code
local TweenService = game:GetService("TweenService")

local blackhole = script.Parent

local angle = blackhole.Angle

local star = workspace.Star

local angleInfo = TweenInfo.new(6,Enum.EasingStyle.Quad,Enum.EasingDirection.In,0,false,0)

local angleTween = TweenService:Create(angle, angleInfo, {Value = 10*math.pi})

angle.Changed:Connect(function(value)

local radius = 40*(10*math.pi - value)/(10*math.pi)

star.Position = blackhole.Position + radius*Vector3.new(math.cos(value), 0, math.sin(value))

end)

blackhole.ClickDetector.MouseClick:Connect(function()

star.Position = blackhole.Position + Vector3.new(40,0,0)

angleTween:Play()

end)

Just set up your tween for the Value instance, and then connect your function to the it’s .Changed event, and that’s it. I used a click detector to activate the tween but that’s not important here

hope this helps :slight_smile:

13 Likes