The old way of having an AI finding the closest player in a range was just repeatedly looping a function on the server that compared every players magntiude relative to the NPC. But this sucks when you have 50+ NPC’s or so. What more efficient methods possibly involving the client does anybody suggest I use for my Enemy AI, more specifically the way that it finds the closest player.
One thing I’d go for is client-sided checking. It is a complicated way, but can boost performance incredibly if done right.
You do not even need parts on the server side. What this accomplishes is lots of server load is receided and clients handle it.
One example way is to track every single enemy in a server side table with their position data, and sending info every 0.1 seconds (with RunService.Heartbeat).
Clients then get the info for each enemy, calculate the nearest player, and send the info back to the server.
Please note that moving should also be done on the client-side, but make sure you track everything correctly on the server side to stop bypassers (third-party exploiters)
You could possibly do some really fancy optimization stuff like quadtrees or octrees.
However I don’t think you should be running into any significant performance issues with your current setup, monitor script performance to see if you really need to do anything.
Magnitude checks are just math, and really aren’t noticable until you start getting into big numbers. A much better improvement to preformance is to have a single script control all the NPCs instead of having 50+ scripts control one NPC each.
Assuming that hasn’t been done already, the next thing would be using client-sided NPCs, though that’s significantly harder.
I’m making an Enemy AI system that has 100+ calculations (Attribute, FIndFirstChild, magnitudes, state-checking, etc.) every heratbeat on the server and it’s suprisingly performant despite other code also being decently server-intensive. My system runs fine on around 20-70 different NPCs. I would try keeping it on the server. Allat fancy octree quadtree multithreading stuff is way too confusing for me ngl
Quadtree/octree for sure as others have mentioned. Also consider memoizing calls that made from about the same position. It’s okay if it’s not 100% accurate as enemies always going for the player that’s exactly closest could look too robotic. All this said, these calculations are not that expensive in the grand scheme of things, you’re probably spending more just on function calls than actual math.