I’m trying to make a tool that will spawn a cage that updates its X and Y positions to the closest player, so that it can trap them inside of the cage before the cage explodes. But I’m facing the issues of
Game Lag Caused By The Script
The Cage Model teleporting to the player instead of gradually hovering to the players position
And The Cage Model itself lagging.
There are no error’s, so anyone know how I can solve this issue?
local Model = script.Parent
local PrimaryPart = script.Parent.PrimaryPart
local players = game.Players:GetPlayers()
local characters = {}
local followZone = Region3.new(PrimaryPart.Position - Vector3.new(125, 1, 125), PrimaryPart.Position + Vector3.new(125, 100, 125))
local partsInFollowZone = {} -- Parts in the region3
-- local captureZone = Region3.new(PrimaryPart.Position - )
while task.wait() do
for i, v in pairs(workspace:GetPartBoundsInBox(followZone.CFrame, followZone.Size)) do
table.insert(partsInFollowZone, v)
end
for i, v in pairs(partsInFollowZone) do
if game.Players:GetPlayerFromCharacter(v.Parent) then
Model:MoveTo(v.Parent:FindFirstChild("HumanoidRootPart").Position)
end
end
end
Using while task.wait() is an inherentley laggy solution, as opposed to using game:GetService("RunService").Heartbeat which should also fix your cage model issues as this uses the physics engine rather than raw loopage.
Not true at all. The performance difference is incredibly neglible, and from previous test I’ve done myself, I’m not even entirely sure if it’s there.
Heartbeat doesnt use the physics engine either, it runs after physics simulation has completed. And task.wait() is literally the same as using heartbeat:wait() anyway.
No worries. Anyway it’s laggy because you needlessly run what is essentially the exact same loop twice, and then perform a check on each part to see if they’re a player character, but most importantly, you call the Model:MoveTo function every single time a part has a character as it’s parent (many many many)and never reset the partsInFollowZone table.
This means that to begin with, you’re already calling Model:MoveTo waaay too much, but as the script runs, it only increases further and further.