Script is causing game lag

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
6 Likes

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.

1 Like

But the issue with that is that I’m doing this in a server script, so won’t I not be able to use RunService.Heartbeat?

1 Like

Yes you can. Rather than using the clients frames, it instead uses a frame before a physics calculation is made.

2 Likes

Ok so it ended up working but, the game is insanely laggy now, I’m averaging around 1400+ ping…

1 Like

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.

1 Like

I didnt reply to you my guy haha

1 Like

Oh I’m sorry, I didn’t check the usernames and who posted the posts

kind of tired right now…

1 Like

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.

1 Like

So other than removing everything in the table afterwards, do you think I can use something that can replace the MoveTo() function?

1 Like

You don’t need to, but yes you can set the cframe directly.