Best way to make an NPC follow you

Hello,

I know several methods of making NPC detect a player through magnitude and making it follow you.

However, my question arises for efficiency.

What would be the best method of doing this?
I know that running while () do loops could cause some latency due to the script performance being high.

Thanks

2 Likes

Feel free to post the methods you would like help comparing, there are usually an arbitrary amount of optimization/balancing that can be done on most methods as well

Maybe just weld a non-cancollide part to the NPC and detect when that’s touched?

Just make the wait interval longer. What code are you working with? I strongly doubt you’re running into any efficiency issues. Calculating the distance between two points is not computationally expensive.

On the other hand, if you’re doing something really expensive (like using an old zombie script that iterates through the entire Workspace every approx. 1/29th of a second… shudder), then yes of course you might experience some kind of latency.

1 Like

Using pathfinding service, you could have the NPC follow a path to you… And then update the path continuously (at some rate).

And if the NPC is within like 15 studs, there shouldn’t really be a need to have them come any closer.

1 Like

I may not be getting the question, but you could use RunService.Heartbeat

Isnt that for client only?

RunService.Heartbeat and RunService.Stepped exist on the client and server, while RunService.RenderStepped is limited to the client.

The one addition I would make depending on your map is to ray cast the target, and just ignore pathfinding if there are no obstructions. This has the benefit of being more efficient in some cases since rays are much cheaper to run, but will cause problems if there are holes in the map.
If you aren’t using pathfinding, then you shouldn’t run into problems unless you are comparing a lot (thousands) of distances every 1/30th of a second.

2 Likes

Well, if he used pathfinding service, he would only have to update the path and target position if the user is like 5 studs from the last target position recorded.

Meaning that, if you were walking in a direction, the NPC pathfinding path would only have to update 3 - 4 times a second (rather than 30 times a second as you stated -if the player is walking at the default 16 walkspeed)

And if the player is falling, then you can ignore pathfinding until the player has landed.

1 Like