How to check how far is a player from an NPC?

Hey there, this is a quick question. How would I go about to check how far an NPC is from a player, and if it is, for example, 10 studs away, then it would do something.

you can use .Magnitude like so:

(character.Position - NPC.Position).Magnitude

so It would be formatted in a local script:

local RootPart = game.Players.LocalPlayer.Character.HumanoidRootPart
local NPC = game.NPC.Head

while true do
    if (RootPart.Position - NPC.Position).Magnitude <= 10 then
        -- do something
    end
    wait()
end
3 Likes

Use .magnitude, the solution to your problem should be easy to find through simply searching through the forum( there are plenty of topics on it) or the wiki

local Npc = ---Npc
local player = game.players.Localplayer

local dist = (Npc.HumaniodRootPart.Position - player.HumaniodRootPart.Position).magnitude

  if dist <= 10 then

---code
end
3 Likes

Magnitude returns the length of a given vector. To get the distance, you would do: (thing1.Position - thing2.Position).Magnitude. Magnitude is a scalar, so you can compare it with a value.

Like so:

local dist = (thing1.Position - thing2.Position).Magnitude

if dist <= 10 then
    print("player is less than 10 studs away from the NPC")
end

print(thing1.Name .. " is " .. dist .. " studs away from " .. thing2.Name)

Thing1 and Thing2 are basically examples, so you need to replace them with the player’s hrp (humanoid root part) and the NPC’s hrp

2 Likes

I realize the answer has been covered three times, but to give you an idea of what’s basically happening. magnitude takes 2 vector positions, and through subtraction, gives you the distance between the two points.

1 Like