I have a few ideas on how to achieve this. Specifically I want to check if a player is at least (for example) 30 studs from a given position. This would be checked every 0.5 - 1 seconds for at least 5 seconds.
Method 1: using In Pairs, cycle through all the players and check if the magnitude of their HumanoidRootPart. However, I’m not too sure what the max player count will be and could be around 20 - 30. Note that a lot would already be going on.
Method 2: to use FindPartsInRegion3, but I heard this is quite straining on the server, plus I am terrible at vector maths so I would clone a dummy region part to act as the zone and use its corners as reference. And then to check for parts named “HumanoidRootPart” in that region.
Which method would be best and quick for this scenario? Does anyone have any other ideas?
Definitely suggest using method 1, because magnitudes are an efficient and and accurate way of getting distances. For the In Pairs for loop, you can simply get the amount of players on the server by using #game.Players:GetChildren().
I see, would this be healthy for the server if I were to do this multiple times over a few seconds? Because I plan on using a projectile (a type of rocket) to fly to a position given by the players mouse, and as it flies, check every 1 second for the closest player and then steer towards them.
The best method of those listed would definitely be using magnitude; less intensive, easier to code etc etc.
However, since you are dealing with just players, you could use a built-in api that Roblox provides from the C-side that will make performance slightly better: Player:DistanceFromCharacter(vector3)
local vecPoint = Vector3.new(30,0,0)
local closestPlayer, smallestMagnitude = nil,math.huge
for _, player in pairs(game.Players:GetPlayers()) do
local distance = player:DistanceFromCharacter(vecPoint)
if distance < smallestMagnitude then
smallestMagnitude = distance
closestPlayer = player
end
end