I am trying to create an effective train movement system without relying on physics, as it can break sometimes. The script basically takes the time in between frames, multiplies it by the speed, adds it to the distance traveled between 2 nodes, divides that by the section length, and lerps the bogey to the new alpha.
- What do you want to achieve? Keep it simple and clear!
I would like the distance between the train cars to be the same, 5 studs.
- What is the issue? Include screenshots / videos if possible!
The issue is that sometimes it does not stay constant/nearly constant.
(skip to 0:50 to see it working as intended)
- What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I’ve tried making the starting speed 0, then setting it to something. I have tried looking for solutions, but to no avail.
local cont = true game:GetService("RunService").Heartbeat:Connect(function(dt) print("Time in between frame: "..dt) print("Current Speed: "..script.Parent.CurrentSpeed.Value) for i = 1, script.Parent.Cars.Value do local v = script.Parent:FindFirstChild("Car"..tostring(i)) print(v.Name.." Continuation: "..tostring(cont)) if cont == true then if v:IsA("Model") then print(v.Name.." Speed: "..script.Parent.CurrentSpeed.Value) local train = v local nodes = train.Parent.Parent.Parent.Nodes local loco = train.Locomotive local front = loco.Front local back = loco.Back local base = train.Base local gap = (front.Position-back.Position).Magnitude local function NextNode(target) target.Current.Value = target.Current.Value.NextNode.Value end local function Move(target, dt) local curNode = target.Current.Value local nextNode = target.Current.Value.NextNode.Value if nextNode then local distanceTraveledOnSection = (target.Position-curNode.Position).Magnitude local sectionLength = (nextNode.Position-curNode.Position).Magnitude local alpha = (distanceTraveledOnSection+script.Parent.CurrentSpeed.Value*dt)/sectionLength target.CFrame = curNode.CFrame:Lerp(nextNode.CFrame, alpha) if alpha >= 1 then NextNode(target) end else script.Parent.CurrentSpeed.Value = 0 cont = false print("STOP!") return end end Move(front, dt) Move(back, dt) base.CFrame = CFrame.new(back.Position, front.Position)*CFrame.new(0,7.5,-gap/2) end end end end)
Help would really be appreciated!