BACKGROUND INFO. I have this script. What this script does is “Help a player stay on a tweening part”
How it works: It “raycasts” below the character’s leg too check for a part called “TrainFloor” by ignoring all other parts.
If a TrainFloor is detected, that means the Player is standing on the train and moves the Players CFrame relative to the trains.
ISSUE:
The script is causing intense lag. When I enabled this script and ran it on different devices on different accounts, it dropped my FPS from a smooth 60 to 15-10 FPS.
When disabled, everything runs smoothly.
*Listing devices specifications at the end
Here is the script. (Game uses R6 Avatars)
local Players = game:GetService("Players")
local player = game.Players.LocalPlayer
local RunService = game:GetService('RunService')
local LastTrainCFrame
local Function
local Function2
local TRAIN_BASE_NAME = "TrainFloor"
local DoOnce = false
local LastHit = nil
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
Function = RunService.Heartbeat:Connect(function()
local RootPart = player.Character:WaitForChild("Right Leg")
local Ignore = { player.Character }
for _, part in game.workspace:GetDescendants() do
if part.Name ~= "TrainFloor" and part.Parent.Name ~= "Workspace" then
table.insert(Ignore, part)
end
end
raycastParams.FilterDescendantsInstances = Ignore
local result = workspace:Raycast(RootPart.CFrame.p, Vector3.new(0, -500, 0), raycastParams)
if not result then
return --nothing below the character
end
local Hit, Position, Normal, Material = result.Instance, result.Position, result.Normal, result.Material
--------------------------------
--print(Hit.Name)
if DoOnce == false then
DoOnce = true
LastHit = Hit
end
if LastHit == Hit then
--Do Nothing
elseif LastHit ~= Hit then
LastHit = Hit
LastTrainCFrame = nil
end
local Train = nil
local TrainCF = nil
local Rel = nil
if Hit and player.Character.Humanoid.Sit == false then
--print("slay")
-- MOVE PLAYER TO NEW POSITON FROM OLD POSITION:
Train = Hit
if LastTrainCFrame == nil then -- If no LastTrainCFrame exists, make one!
LastTrainCFrame = Train.CFrame -- This is updated later.
end
TrainCF = Train.CFrame
Rel = TrainCF * LastTrainCFrame:inverse()
LastTrainCFrame = Train.CFrame -- Updated here.
RootPart.CFrame = Rel * RootPart.CFrame -- Set the player's CFrame
else
LastTrainCFrame = nil
Train = nil
TrainCF = nil
Rel = nil
end
Function2 = player.Character.Humanoid.Died:Connect(function()
Function:Disconnect() -- Stop memory leaks
Function2:Disconnect() -- Stop memory leaks
end)
end)
Here is the script. There are no errors in output. The script works as intended.
Devices specifications
Tested on computer: Has an i7 processor, Laptop
Tested on Phone: Samsung
Any help is appreciated. Please ask for more information and I will give you it
I have been working on this game for 6 months, and this is stopping me for progressing further. Any help is appreciated