How to get the closest player

So im making a bot AI blah blah blah
And im having some trouble detecting the closest player
How i would make this work?

The script

local Rake = script.Parent
local PathfindingService = game:GetService("PathfindingService")
local Distance = math.huge

local Values = script.Parent.Values
local Chasing = Values.Chasing
local Walking = Values.Walking

local function getclosestplr()
	for i, player in pairs(workspace:GetChildren()) do
		if player:FindFirstChild("Humanoid") then
			if player.HumanoidRootPart.Position > Distance then
				-- Part that detects the closest player
			end
		end
	end
end

I’m assuming you mean closest relative to your bot.

What you should do is you should loop through all the players in the game and keep track of the distances of the player to your bot.

I’ll edit your code to something like this:

local Rake = script.Parent
local PathfindingService = game:GetService("PathfindingService")

local Values = script.Parent.Values
local Chasing = Values.Chasing
local Walking = Values.Walking

local function getclosestplr()
    local bot_position = YOUR_BOT_POSITION_HERE
    
    local distance = math.huge
    local closest_player_character = nil
    
	for i, player in pairs(workspace:GetChildren()) do
	    -- you have put player, but this is really the players character
		if player:FindFirstChild("Humanoid") then

		    local player_position = player.HumanoidRootPart.Position
		    local distance_from_bot = (bot_position - player_position).magnitude
		    
			if distance_from_bot < distance then
			    distance = distance_from_bot
			    closest_player_character = player
			end
		end
	end
	
	return closest_player_character
end

Make sure to edit this line

local bot_position = YOUR_BOT_POSITION_HERE
1 Like

Oh, but what did you mean with bot position?

The bot you’re making, does it have some sort of primary part you can use to get it’s position? For example, for a player we use the position of the HumanoidRootPart,

Character.HumanoidRootPart.Position

Ohhh yeah it does, just didnt knew it was that bc it was position and usually i see local HumanoidRootPart or local NPC