You can write your topic however you want, but you need to answer these questions:
What do you want to achieve? Keep it simple and clear!
I want to find the closest player from humanoidRootPart
What is the issue? Include screenshots / videos if possible!
The script does NOT print out the player’s Name
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I have tried to use DistanceFromCharacter but it will still not work
local zombie = script.Parent
local HumanoidRootPart = zombie.HumanoidRootPart
local players = game:GetService("Players")
local missile = zombie.Backpack.Missile
local player = game.Players.LocalPlayer
game:GetService("RunService").Heartbeat:Connect(function()
for i, player in pairs(players:GetPlayers()) do
local distance = player:DistanceFromCharacter(HumanoidRootPart.Position)
if distance > 500 then
print(player)
end
end
end)
You write that you’d like to find the closest Player, however the code you posted would only print the Player when they are more than 500 studs away from the zombie’s HumanoidRootPart. If you’d like a function to find the nearest player to Zombie, you would not want to use the DistanceFromCharacter method here as this method returns 0 when the Player has no character. Instead you might use a function like this:
local Players = game:GetService("Players")
function getNearestPlayerToPart(part)
local nearestPlayer = nil
local distanceToNearest = math.huge
for _, player in Players:GetPlayers() do
local char = player.Character
local hrp = if char then char:FindFirstChild("HumanoidRootPart") else nil
if hrp then
local dist = (hrp.Position - part.Position).Magnitude
if dist < distanceToNearest then
nearestPlayer = player
distanceToNearest = dist
end
end
end
return player --If there are no Players in the game or none with a Character, this will return nil
end
--Based on the code you provided, you would call the function passing in the variable `HumanoidRootPart` (of the zombie)
local nearestPlayer = getNearestPlayerToPart(HumanoidRootPart)