I’m making a game about a train, and the background (composed of ~1500 parts at its minimum) moves instead of the train to create the illusion of movement. I did this because moving the train would cause players to lag, awkwardly fling around the place, and there would be no way to reset the train to stop it from going into infinity. My script works, but it creates a TON of lag. I understand this is due to the repetition and the way the script runs every frame. How could I optimize it to run better?
This script runs clientside.
-- This script tweens rails, terrain, and decoratins.
local ServerScriptService = game:GetService("ServerScriptService")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local snapMoving = workspace.SnapMoving
local primaryPart = snapMoving.PrimaryPart
local primaryPartLocs = {}
-- This bit makes a table of all of the different places primaryPart will be moved to.
for x = 1, 7, .875 do
primaryPartLocs[#primaryPartLocs+1] = CFrame.new(primaryPart.Position.X, primaryPart.Position.Y, primaryPart.Position.Z + x)
end
-- AAAAAAAH!!! Running this piece of GARBAGE uses 25% of the CPU! It exists to move the entire model with all 1428 parts. Real taxing.
while true do
for x = 1, 7 do
snapMoving:SetPrimaryPartCFrame(primaryPartLocs[x])
RunService.Heartbeat:Wait()
end
end