I have some knowledge on it but I can't quite get it figured out. I know that you have to use magnitude but I'm just having trouble. It should be very simple. Can someone help? Thanks.
How do you get the distance between a player and a part?
4 answers
(Player.HumanoidRootPart.Position - Part.Position).Magnitude
or this if you are using the player class instead of the model itself in game
(Player.Character.HumanoidRootPart.Position - Part.Position).Magnitude
This would get you the distance. (Change "HumanoidRootPart" to whatever part you want in the player like "UpperTorso".
You use magnitude and both of the parts positions
print((part1.Position - part2.Position).magnitude)
That code would print the distance, in studs, of the two parts
Use magnitude
local plr = game.Players.LocalPlayer
repeat wait() until plr.Character
local chr = plr.Character
local hrp = chr:FindFirstChild("HumanoidRootPart") -- Get HumanoidRootPart, but you can use Torso, UpperTorso, etc..
spawn(function()
while wait()do
-- check if player distance is <=10(mag) then
if (hrp.Position - game.Workspace["PartName"].Position).Magnitude <=10 then
print("In mag")
-- Your code here
end
end
end)
###Sidenote
I see some answers already but none of them are explaining the concept of (a - b).Magnitude and are ignoring roblox has a built in function for this case.
Question
How do you get the distance between a player and a part?
Answer
Roblox has a method for player instances called :DistanceFromCharacter.
You pass a Vector3 and it will return the distance from the character's head to the position you passed.
Example Code
In this code it will get the distance from part to the player's head then will output the distance.
local player = ... --// reference to your player
local part = --// reference to your part
local distance = player:DistanceFromCharacter(part.Position)
print(player.Name, "is", distance, "studs away!")
Extra Resources
Information
(broad explanation incoming...)
where a and b are both vectors,
a - b will be the difference between those vectors.
the .Magnitude property will return the length of a vector, invoking it on the difference of a - b will result in the distance between a and b.
Links:
(For a rigerous concept on how (a - b).Magnitude works: ) https://en.wikipedia.org/wiki/Euclidean_distance
(Side Route API Documentation for DistanceFromCharacter since the main page is down)
https://developer.roblox.com/en-us/api-reference/class/Player
This discussion is preserved as it was. New answers, comments, and votes are closed.
