Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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.

1 comment

2 answers

✓ Accepted answer

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.

4 comments

0

Im a noob at scripting, but could this work in a local script?

0

Yes.

0

what do you mean with zombie's

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.

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 >

1 comment

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.