Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Efficient way of checking characters proximity to position?

I would like to know if there is an objectively better / more efficient way to achieve the same functionality as the following code.

Note: This code is in a LocalScript located inside StarterPlayerScripts.

local NPCModule = require(script.Parent)
local Player = game.Players.LocalPlayer
local Character = game.Workspace:WaitForChild(Player.Name)
local Humanoid = Character:WaitForChild("Humanoid")

local NPCs = {}
for _, NPC in pairs(game.Workspace.NPCs:GetChildren()) do
	table.insert(NPCs, NPC)
end

Humanoid.Changed:Connect(function()
	for _, NPC in pairs(NPCs) do
		local NPCPosition = NPC.HumanoidRootPart.CFrame.p
		local CharacterPosition = Character.HumanoidRootPart.CFrame.p
		local MaxDistance = 10
		if (NPCPosition - CharacterPosition).magnitude <= MaxDistance then
			--Do stuff
		end
	end
end)

1 answer

✓ Accepted answer

Well, that's probably the best way to do it. I don't know what else you could do... raycasting? Either way, the way you are doing it right now is probably the best/better one.

Actually, on second thought, if you use the Running event of Humanoid that might be better.

This discussion is preserved as it was. New answers, comments, and votes are closed.