Below is a short code that I scripted. It gets the distance between the NPC's torso and the player torsos. If it is less than 5, it will print "We're within 5 studs." When I looked at the torso's position while I was walking, I noticed it wasn't changing, is there anything else besides position that I can use to check if the player is within 5 studs of the NPC?
This is in a local script in StarterPlayerScripts.
--Variables local player = game:GetService("Players").LocalPlayer local character = player.Character or player.CharacterAdded:wait() local torso = character:WaitForChild("Torso") local npc = game.Workspace.NPC or game.Workspace:WaitForChild("NPC") function getDistance(distance1, distance2) local distance = (distance2 - distance1).magnitude print(distance) return distance end local distance = getDistance(torso.Position, npc.Torso.Position) while wait(1) do print(distance) if distance <= 5 then print("We're within 5 studs.") end end
You just have one problem. getDistance() updates the distance variable once. Make your while wait(1) do loop like the bellow code:
while wait(1) do local distance = getDistance(torso.Position, npc.Torso.Position) print(distance) if distance <= 5 then print("We're within 5 studs.") end end
I forgot to say that this works because 'distance' was only changed one time (at the start) giving you the same distance because it was never changed.
There is one obvious problem, and that is that you only check for the distance once, then use that. Instead, you need to check inside the loop, like this:
while wait(1) do local distance = getDistance(torso.Position, npc.Torso.Position) print(distance) if distance <= 5 then print("We're within 5 studs.") end end
You should also be careful, as if the player dies then you will need to reset the torso
variable.
However, through experience I've run into an additional problem where the player's torso position does not change as expected. You could work around this by using the DistanceFromCharacter
function of Player:
while wait(1) do local distance = player:DistanceFromCharacter(npc.Torso.Position) print(distance) if distance <= 5 then print("We're within 5 studs.") end end
While this only works with players, it's a lot simpler and isn't affected by the player dying (note that it measures distance from the head rather than torso, but the difference is negligable).