How to sync tweens running in for loop?

I am trying to create a for loop that makes the surroundings in the background seem like they are moving. I am using tweens to tween 4 parts backwards to create the illusion of movement, but after every loop there is a gap of time between the tween starting again and the tween finishing, ruining the illusion. How can I fix this?

local Surroundings = workspace.Surroundings
local BackPos = Surroundings['1'].PrimaryPart.CFrame
local MiddlePos = Surroundings['2'].PrimaryPart.CFrame
local FrontPos = Surroundings['3'].PrimaryPart.CFrame
local EndPos = Surroundings['4'].PrimaryPart.CFrame

local TweenService = game:GetService("TweenService")

local TweenTime = 1
local Info = TweenInfo.new(
	TweenTime
)

while true do
	for i,part in Surroundings:GetChildren() do
		if part.PrimaryPart.CFrame == BackPos then
			local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = MiddlePos})
			Tween:Play()
		elseif part.PrimaryPart.CFrame == MiddlePos then
			local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = FrontPos})
			Tween:Play()
		elseif part.PrimaryPart.CFrame == FrontPos then
			local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = EndPos})
			Tween:Play()
		elseif part.PrimaryPart.CFrame == EndPos then
			task.wait(TweenTime*.9)
			part.PrimaryPart.CFrame = BackPos
		end
	end
	task.wait(TweenTime)
end

I used task.spawn() and task.delay() to run your code separately.

local Surroundings = workspace.Surroundings

local BackPos = Surroundings['1'].PrimaryPart.CFrame
local MiddlePos = Surroundings['2'].PrimaryPart.CFrame
local FrontPos = Surroundings['3'].PrimaryPart.CFrame
local EndPos = Surroundings['4'].PrimaryPart.CFrame

local TweenService = game:GetService("TweenService")

local TweenTime = 1
local Info = TweenInfo.new(
	TweenTime
)

while true do
	for i,part in Surroundings:GetChildren() do
		task.spawn(function()
			if part.PrimaryPart.CFrame == BackPos then
				local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = MiddlePos})
				Tween:Play()
			elseif part.PrimaryPart.CFrame == MiddlePos then
				local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = FrontPos})
				Tween:Play()
			elseif part.PrimaryPart.CFrame == FrontPos then
				local Tween = TweenService:Create(part.PrimaryPart, Info, {CFrame = EndPos})
				Tween:Play()
			elseif part.PrimaryPart.CFrame == EndPos then
				task.delay(TweenTime*.9, function()
					part.PrimaryPart.CFrame = BackPos
				end)
			end
		end)
	end
	task.wait(TweenTime)
end

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