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

How do i use magnitude to find the nearest player in the game?

Asked by
wookey12 174
6 years ago

I made a duplicate of my player and wanted to see if i could make a basic zombie. i looked up pathfinding on the wiki, i know how to use it. but... i need to know how to use magnitude to find out if which players is closest, and they need to be at least 15 studs away. here's what i got so far:

local zombie = script.Parent
local pathfind = game:GetService("PathfindingService")
local players = game.Players:GetPlayers()
while players.Character.UpperTorso.Position.magnitude <= 100 do
local Start = zombie.LowerTorso
end

obviously this won't work.. i just gave that a shot.. and i can't really find any tutorials or anything on the wiki to help me use magnitude.

2 answers

Log in to vote
2
Answered by
UgOsMiLy 1074 Moderation Voter
6 years ago

Try this, it should work.

function FindNearest(position)
    local lowest = math.huge -- infinity
    local NearestPlayer = nil
    for i,v in pairs(game.Players:GetPlayers())
        if v and v.Character then
            local distance = v:DistanceFromCharacter(position)
            if distance < lowest then
                lowest = distance
                NearestPlayer = v
            end
        end
    end
    return NearestPlayer
end

print(FindNearest(position)) -- change position to the position of the Zombie's upper/lower torso, or head.
0
Im a noob at scripting, but could this work in a local script? turbomegapower12345 48 — 6y
0
Yes. JoeRaptor 72 — 6y
0
what do you mean with zombie's SamirDevs 15 — 5y
0
Samir, they're trying to have a zombie finding the distance of the nearest player (I believe), so the function is called "FindNearest(parameter1) the parameter would be a position and the script will print a returned distance between that position and the nearest player. ChristianTRPOC 64 — 5y
Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago
function FindNearestPlayer(StartPlayer)
     local found
     local last = 0
     for i,v in pairs(game.Players:GetPlayers()) do
          local distance = v:DistanceFromCharacter(StartPlayer.Character.HumanoidRootPart.Position)
          if distance < last then
               found = v
          end
          last = distance
     end
return found
end

should work

EDIT: If it doesnt work change the < on line 6 to >

0
"last" on line 3 needs to be math.huge as no positive number is smaller than 0, and "last = distance" should be inside the "if" block. UgOsMiLy 1074 — 6y

Answer this question