How to make a tool to teleport you to closest player

How could I make a tool when activated will teleport you to the closest player I’ve been thinking for a while and even searched on the dev forum but can’t find anything so could anyone please tell me how and I hope you have a great day!

You’d want to gather everyone’s HumanoidRootPart magnitude, and compare them to see which player has the lowest (closest). You could use this:

local players = game:GetService("Players")

local function getClosestPlayer(from) --from = player to compare.
	local closest = {Player = nil, Magnitude = 0}--if there's no players in the server.
	local playerPosition = from.Character:WaitForChild("HumanoidRootPart").Position

	for _, player in pairs(players:GetPlayers()) do
		if player == from then continue end
		--for every player do,
		local targetPosition = player.Character.HumanoidRootPart.Position
        local magnitude = (targetPosition - playerPosition).Magnitude
		if magnitude < closest.Magnitude or closest.Magnitude == 0 then
			--if closer then,
			closest["Player"] = player; closest["Magnitude"] = magnitude
		end
	end

	return closest.Player --returning the player or nil.
end

local player = players.LocalPlayer

local closestPlayer = getClosestPlayer(player)
if closestPlayer then --if got player then
	print("The closest player is ", closestPlayer.Name)
    player.Character.HumanoidRootPart.Position = closestPlayer.Character.HumanoidRootPart.Position
end

Edit: accidentally saved the root’s position instead of the actual magnitude. Fixed.

3 Likes