Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Torso position isn't changing, how to check if player is within 5 studs of the NPC?

Asked by
Master_JJ 229 Moderation Voter
8 years ago

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.

01--Variables
02local player = game:GetService("Players").LocalPlayer
03local character = player.Character or player.CharacterAdded:wait()
04local torso = character:WaitForChild("Torso")
05local npc = game.Workspace.NPC or game.Workspace:WaitForChild("NPC")
06 
07 
08function getDistance(distance1, distance2)
09    local distance = (distance2 - distance1).magnitude
10    print(distance)
11    return distance
12end
13 
14local distance = getDistance(torso.Position, npc.Torso.Position)
15 
View all 21 lines...

2 answers

Log in to vote
2
Answered by 8 years ago
Edited 8 years ago

You just have one problem. getDistance() updates the distance variable once. Make your while wait(1) do loop like the bellow code:

1while wait(1) do
2    local distance = getDistance(torso.Position, npc.Torso.Position)
3    print(distance)
4    if distance <= 5 then
5        print("We're within 5 studs.")
6    end
7end
  • edit

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.

0
THanks Master_JJ 229 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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:

1while wait(1) do
2    local distance = getDistance(torso.Position, npc.Torso.Position)
3    print(distance)
4    if distance <= 5 then
5        print("We're within 5 studs.")
6    end
7end

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:

1while wait(1) do
2    local distance = player:DistanceFromCharacter(npc.Torso.Position)
3    print(distance)
4    if distance <= 5 then
5        print("We're within 5 studs.")
6    end
7end

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).

Answer this question