Tween moves 10 studs down when completed

This script is meant to move a sphere back and forth between two points infinitely. But whenever the sphere gets to a point it moves down about 10 studs and it keeps adding up over time.

local TweenService = game:GetService("TweenService")

local Sphere = script.Parent.Machine:WaitForChild("Sphere")

local Point1 = script.Parent.Point1
local Point2 = script.Parent.Point2

local function TweenSphere()
    Sphere.CFrame = Point1.CFrame
    local tweenInfo = TweenInfo.new(3, Enum.EasingStyle.Linear, Enum.EasingDirection.In, 0, false)
    
    local goal1 = {CFrame = Point2.CFrame}
    local Tween1 = TweenService:Create(Sphere, tweenInfo, goal1)
    Tween1:Play()
    
    Tween1.Completed:Connect(function()
        local goal2 = {CFrame = Point1.CFrame}
        local Tween2 = TweenService:Create(Sphere, tweenInfo, goal2)
		Tween2:Play()
		Tween2.Completed:Connect(TweenSphere)
    end)
end

TweenSphere()


You can use the TweenInfo to specify a looping tween without needing to constantly call it. If you give a negative number for the repeatCount argument, it will repeat forever, and if you want the tween to move back and forth, set reverses to true.

Sphere.CFrame = Point1.CFrame

local tweenInfo = TweenInfo.new(3, Enum.EasingStyle.Linear, Enum.EasingDirection.In, -1, true)
local tween = TweenService:Create(Sphere, tweenInfo, {CFrame = Point2.CFrame})
tween:Play()

Do you notice that your code creates infinite connections? Every time the script is finished it creates a new connection that calls the same function that will recreate the same function, never ending.

I would recommend changing your code to this:

local TweenService = game:GetService("TweenService")

local Sphere = script.Parent.Machine:WaitForChild("Sphere")

local Point1 = script.Parent.Point1
local Point2 = script.Parent.Point2

local function TweenSphere()
    Sphere.CFrame = Point1.CFrame

    local tweenInfo = TweenInfo.new(3, Enum.EasingStyle.Linear, Enum.EasingDirection.In, 0, false)   
    local goal1 = {CFrame = Point2.CFrame}
    local goal2 = {CFrame = Point1.CFrame}

    local Tween1 = TweenService:Create(Sphere, tweenInfo, goal1)
    local Tween2 = TweenService:Create(Sphere, tweenInfo, goal2)

    while true do
        Tween1:Play()    
        Tween1.Completed:Wait()
      
        Tween2:Play()
        Tween2.Completed:Wait()
    end
end

TweenSphere()

You don’t need to insert a task.wait() in the while because the Tween already provides enough time for the code not to crash.

Thank you, the reason I had it have multiple tweens was because I was using a different EasingStyle but I have since changed it to linear.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.