I made a script that detects if a player is nearby. If they are nearby, then there is another function that detects if the nearest player is looking directly at the object. The problem i am having, is when one player is near it already and another player walks closer to it, it's still staying locked on the first person even though they're farther away then the player that walked close by.
Does anyone know how i can actually find the nearest player, or if i'm doing anything wrong here?

local NTDISTANCE = 100000
while wait() do
	local TARGETPART
	local TARGETMODEL
	for i,e in pairs(workspace:GetChildren()) do
		if e:FindFirstChild("HumanoidRootPart") and e:FindFirstChild("Humanoid") and e:FindFirstChild("Head") and e:FindFirstChild("Humanoid").Health ~= 0 and e.Name ~= script.Parent.Name then
			local HRP = e.HumanoidRootPart
			if (HRP.Position-SCP.HumanoidRootPart.Position).Magnitude < NTDISTANCE then
				TARGETPART = HRP
				TARGETMODEL = HRP.Parent
			end
		end
	end
	if TARGETPART ~= nil and canSee("code") then
		--Start doing stuff.
	end
end

4 comments

2

You never set the value of NTDISTANCE so no matter what the second person looped through will always be TARGETPART

1

Should set local NTDISTANCE = 100000 at start of the while loop and then when you set TARGETPART also set NTDISTANCE to (HRP.Position - SCP.HumanoidRootPart.Position).Magnitude

0

Okay, i'll try that.

1

It worked! Thanks so much. If you write an answer, i'll be glad to accept it.