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
7 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:

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

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
7 years ago

Try this, it should work.

01function FindNearest(position)
02    local lowest = math.huge -- infinity
03    local NearestPlayer = nil
04    for i,v in pairs(game.Players:GetPlayers())
05        if v and v.Character then
06            local distance = v:DistanceFromCharacter(position)
07            if distance < lowest then
08                lowest = distance
09                NearestPlayer = v
10            end
11        end
12    end
13    return NearestPlayer
14end
15 
16print(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 7 years ago
Edited 7 years ago
01function FindNearestPlayer(StartPlayer)
02     local found
03     local last = 0
04     for i,v in pairs(game.Players:GetPlayers()) do
05          local distance = v:DistanceFromCharacter(StartPlayer.Character.HumanoidRootPart.Position)
06          if distance < last then
07               found = v
08          end
09          last = distance
10     end
11return found
12end

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 — 7y

Answer this question