I made a peace of code to get ever part in the workspace and loop through them all, but how would I see how far away the player is from a part if it has a certain name?
3 Likes
Subtract one part’s position from another part’s position and then read its .Magnitude property
local part1 = workspace.Part1
local part2 = humanoidRootPart -- character's humanoid root part
local distance = (part1 - part2).Magnitude
1 Like
You could use magnitude
to check the length between both objects’ positions.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local Object = game.Workspace:WaitForChild("EnemyPart")
local Distance = (Object.Position - player.Character.HumanoidRootPart.Position).Magnitude
print(Distance)
10 Likes
This code can work if you want to repeatedly get the closest part with a specific name in a loop.
local PS = game:GetService("Players")
local player = PS.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local HRP = char:FindFirstChild("HumanoidRootPart")
local targetNames = {"swisscheese", "zombie", "robloxguy"}
local function GetClosestPart()
local target = nil
local distance = nil
for i,v:BasePart in pairs(workspace:GetChildren()) do
if v:IsA("BasePart") and table.find(targetNames, v.Name) then
local mag = player:DistanceFromCharacter(v.Position)
if target and distance then
if mag < distance then
target = v
distance = mag
end
else
target = v
distance = mag
end
end
end
return target, distance
end
If you’re dealing with players, it’s better to use player:DistanceFromCharacter() instead of .Magnitude because it is more performant and less intensive.
2 Likes