Hello, I am trying to achieve a smooth moving train kit based on nodes. This already works as of itself but lags a lot on server side as it counts each carriage as an individual train. Trains are counted by 2 nodes each.
I tried modifying the script and multiple other solutions to make this work, but it still lags as much server side.
local rs = game:GetService("RunService")
local train = script.Parent
local curSpeed = train.CurrentSpeed
local nodes = train.Parent.Parent.Nodes
local nodeReady = nodes.Parent.NodeReady
local loco = train.Locomotive
local front = loco.Front
local back = loco.Back
local base = loco.Base
local gap = (front.Position - back.Position).Magnitude
local loco_model = loco.Model
local startingNode = train.StartingNode
print("started2")
wait(10)
repeat wait() until nodeReady.Value
function SetStartingNode()
front.Current.Value = nodes:FindFirstChild("Node_" .. startingNode.Value)
back.Current.Value = nodes:FindFirstChild("Node_" .. startingNode.Value)
end
function NextNode(target)
local curNode = target.Current
local nextNode = curNode.Value.NextNode.Value
curNode.Value = nextNode
end
function Move(target, deltaTime)
local curNode = target.Current.Value
local nextNode = target.Current.Value.NextNode.Value
if not nextNode then
curSpeed.Value = 0
return
end
local distanceTraveledOnSection = (curNode.Position - target.Position).Magnitude
local sectionLength = (curNode.Position - nextNode.Position).Magnitude
local newAlpha = ((distanceTraveledOnSection + curSpeed.Value * deltaTime)) / sectionLength
target.CFrame = curNode.CFrame:Lerp(nextNode.CFrame, newAlpha)
if newAlpha >= 1 then
NextNode(target)
end
end
rs.Heartbeat:Connect(function(deltaTime)
Move(front, deltaTime)
Move(back, deltaTime)
base.CFrame = CFrame.new(back.Position, front.Position) * CFrame.new(0,front.Size.Y/2 + base.Size.Y/2,-gap/2)
loco_model:SetPrimaryPartCFrame(base.CFrame * CFrame.new(0,base.Size.Y/2 + loco_model.PrimaryPart.Size.Y/2,0))
end)
SetStartingNode()
I have looked into the Devforum multiple times but have still not found the solution. Please keep me updated.