How to detect how far away the npc is from the player?

Hello, I’m working on a game based off the backrooms And I thought of an idea that I could add a “how far away is the NPC from you: whatever stud” but little did I know, I’m completely clueless on how to do it.

I looked around Devfourm to see if there were any posts about this and I tried doing this

local playerRoot = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
local modelRoot = game:GetService("Workspace").killingEnity.HumanoidRootPart
local distance = (playerRoot.Position - modelRoot.Position).Magnitude 


local radius = 50

if (distance <= radius) then
	script.Parent.Label.Text = "You might wanna run.."
else
	script.Parent.Label.Text = "Entity is not near you."
end

It does not work nor error.
Any help?

2 Likes

Detect the NCP’s CFrame then compare it to the player’s CFrame! :yum:

Doesn’t the players CFrame change every time you move?

1 Like

Yes it is ! :grinning:
It is not what you want ? :thinking:

Since the code is not checking the distance continuously it only prints out once,
So to do that you’ll need to put the code in a loop like so

while wait() do
if (distance <= radius) then
   script.Parent.Label.Text = "You might wanna run.."
else
   script.Parent.Label.Text = "Entity is not near you."
end
end

Hope it helped.

1 Like

alright ill see if this works, be right back.

1 Like

Yes that’s right, I misunderstood the question :sweat_smile:
Sorry …

Weird, doesn’t function at all Aswell? i used print to see if it does work but it only prints the “it is not near you” one Not the “It is near you, run” one.

1 Like

Maybe you miscalculated the distance between the player and the entity ?

local distance = (playerRoot.Position - modelRoot.Position).Magnitude 

You’ll actually need to update this variable whenever the player resets/dies,
which might be why its not working

Maybe try to print the distance to see if you’ve got the right calculation ?

I’ve got it you made a mistakes at the line 2 it not killingEnity but killingEntity ! :grinning:

1 Like

Thats not the error it was the name of the model i felt lazy to name it right, my bad for making i confusing

1 Like

Here, fixed it for you.

local playerRoot = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
game.Players.LocalPlayer.CharacterAdded:Connect(function(char)
    playerRoot = char:WaitForChild("HumanoidRootPart")
end)
local modelRoot = game:GetService("Workspace").killingEnity.HumanoidRootPart
local radius = 50


while wait() do
local distance = (playerRoot.Position - modelRoot.Position).Magnitude 
if (distance <= radius) then
	script.Parent.Label.Text = "You might wanna run.."
else
	script.Parent.Label.Text = "Entity is not near you."
end
end
3 Likes

There we go, thanks FireStryker and IYagyaveer.

1 Like

and thanks for correcting me, ill change that right now. Lol

Have a good day ! :wink:
GG iYagyaveer !

You too.

30 thing. cjdskjfdsljk