Train platforming system

Hello! I’am creating a train system, the train and related all work. But my script which anchors the player to the train is far from perfect. It works when I stay on one cart, but if I try to switch carts or jump to the previous ones. It in most instances instantly teleports to the end of the next cart.

Note: I’ve tried multiple examples and codes shared from previous posts and none of them change the issue.

My code includes the following:

local plr = game.Players.LocalPlayer
local RunService = game:GetService('RunService')

repeat wait() until plr.Character

local char = plr.Character

local LastTrainCFrame

local Function
local Function2

Function = RunService.Heartbeat:Connect(function()

local RootPart = char:WaitForChild("HumanoidRootPart")

local Ignore = char

local ray = Ray.new(RootPart.CFrame.p,Vector3.new(0,-50,0))

local Hit = workspace:FindPartOnRay(ray,Ignore)

if Hit and Hit:IsDescendantOf(workspace.TrainStuff.Train) then
		local Train = Hit.Parent.PrimaryPart
		if LastTrainCFrame == nil then
			LastTrainCFrame = Train.CFrame
		end
		
		local TrainCF = Train.CFrame 
			
		local Rel = TrainCF * LastTrainCFrame:Inverse()
			
		LastTrainCFrame = Train.CFrame
			
		RootPart.CFrame = Rel * RootPart.CFrame
	else
		LastTrainCFrame = nil
	end
	
	Function2 = plr.Character.Humanoid.Died:Connect(function()
		Function:Disconnect()
		Function2:Disconnect()
	end)

end)

If somebody could help me out with this I’d love to hear.

2 Likes