Better solution for pathfinding magnitude check

Hello, I have a pathfinding NPC, who uses a while true do loop to constantly get each players magnitude and check if it is close enough to chase. Here’s my problem:

local function mainLoop()
while true do


this code is a band-aid solution and can definitely be optimized since having a lot of these in my game will cause lag for the server. Heres the rest of my code that uses the functions in case anybody needs it and wants to optimize any more code. Thanks in advance!

local function seekPlayer()
for i, v in pairs(game.Players:GetPlayers()) do
if v.Character and v.Character:FindFirstChild(“HumanoidRootPart”) then

  	local mag = (v.Character.HumanoidRootPart.Position - npc.HumanoidRootPart.Position).Magnitude
  	if mag < config.MaxRange then


1 Like

Don’t use constant polling to check for the player being close enough. Use a non-collidable part as a “zone” and when a player touches the zone use the event to tell you that they are close enough. Weld the zone onto the NPC and make it massless as well. This way the zone moves with the NPC like a sensor. Just set the size of the zone (1/2 size) as the distance you want the player to be from the NPC. That way when they touch the zone, you automatically know they are within the correct distance. So if the part is size 20, then it can detect a player within 10units from either side of the NPC.

There is one other way that one could argue is better. But its more complicated than this.


The goal here is to spread out the calculations. It can be pretty intense to do distance checks on everything for every npc in the game. And you’re trying to do it 10 times a second for every NPC.

The first thing you could try is put all the NPCs in a list and spread out when they do their calculations. That way you are specifically giving them calculation times. This also means you shouldn’t be calculating every NPC 0.1 seconds over and over, but instead calculating some NPCs before moving onto the next one.

Another option would be to take the distance the player is away from the NPC, and make it so it won’t check for at least as many seconds as it would take for the nearest player to get to them again. So calculate how long it would take for the nearest player to show up and wait that long before checking again. That way you get faster for NPCs that are near players and practically stop calculating for NPCs that are far away.

Another option (though easier for hackers to abuse, but there are methods around it) would be to have each client keep checking which NPCs are near them. Then just have the client tell the server. This way the job is spread across multiple computers. You’ll probably want to add some of the other stuff in there too such as increasing the wait times to ensure that the clients can handle it good enough.

1 Like