Need help with nearest player ai calculation

  1. What do you want to achieve? Keep it simple and clear!

I’m trying to get my Ai to successfully calculate the closest player, but I can’t seem to quite understand it/scrip it.

  1. What is the issue? Include screenshots / videos if possible!

Mainly I just have no idea what to do on fixing my script. It is supposed to get the nearest player, but it keeps choosing the first player it gets.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I’ve tried all of my debugging skills, I have not found a similar post on this forum.

local AiCharacter = script.Parent 

local Humanoid = AiCharacter:FindFirstChild("Humanoid")

local WaypointFolder = workspace:FindFirstChild("WayPoints")

local Target = false

local AgroDistance = 100 -- in studs

local AlreadyNearestPlayer = nil 

local PossibleNearestPlayer = nil

local NearestPlayerDistance = math.huge





-- Get Nearest player function 

local function GetNearestPlayer()
	
	local Players = game.Players
	
	for _,Player in pairs(game.Players:GetPlayers()) do
		local PlayerCharacter = Player.Character
		
		if PlayerCharacter then
			local Humanoid = PlayerCharacter:FindFirstChild("Humanoid")
			if Humanoid then
				local PossiblePlayerDistance = (AiCharacter.HumanoidRootPart.Position - PlayerCharacter:FindFirstChild("HumanoidRootPart").Position).Magnitude 
			
				if PossiblePlayerDistance then
					if PossiblePlayerDistance < NearestPlayerDistance then
						NearestPlayerDistance = PossiblePlayerDistance
						AlreadyNearestPlayer = Players
					end
				end
			end
		end
		return AlreadyNearestPlayer
	end
	
end


-- Find Random walkpoint in the map and walk to it

local function Patrol()
	
end




-- We are going to be using pathfinding service in order for the best pathing on the player


while task.wait(1) do
	-- Find the nearest player
	
	local NearestPlayer = GetNearestPlayer()
	
	print(NearestPlayer)
	
	-- Check to see if it close enough
	
	
	-- If not close enough, then patrol
	
	
	-- If the player is close enough, then walk to the player and disable patroling 
end
1 Like

[quote="InfernoProgrammer11, post:1, topic:3569644, username:InfernoProgrammer11”]
return AlreadyNearestPlayer
[/quote]
return breaks the loop, hence the issue. In another word you don’t really need it there! Delete that line and your script should work.

so then if that breaks the loop. Then how am I supposed to return the nearest player from the function since the function is tied to a variable?

You can define a variable for the nearest player in the very beginning of the function, then return the variable in the end of the function. Do all this outside the loop!

That is if you really want to use return, because if you don’t it will still work, since you defined the variable outside the function, so you can just use that.

I apologize but my brain can’t figure out your solution. Do you mind showing me an example?

local AlreadyNearestPlayer

local function GetNearestPlayer()
	-- find the player
	AlreadyNearestPlayer = "the nearest player"
end

while task.wait(1) do
	GetNearestPlayer()
	-- then you have AlreadyNearestPlayer being the nearest player, 
	-- so you can directly use the variable
end

You don’t need to store the function as a variable.

table.sort() is what I use for this.

local players = game:GetService("Players")

local function GetNearestPlayer()
    local npcPos = AiCharacter.HumanoidRootPart.Position
    local distances = {}

    for _, player in players:GetPlayers() do
        local character = player.Character
        if not character then return end
        
        local root = character.PrimaryPart
        if not root then return end

        local rootPos = root.Position
        local magnitude = (rootPos - npcPos).Magnitude
        table.insert(distances, {
            player = player
            magnitude = magnitude
        }
    end

    table.sort(distances, function(a, b)
        return a.magnitude < b.magnitude
    end)

    local nearestPlayer = distances[1]
    return nearestPlayer
end

Typed it out here, but should work.
distances is the order of players nearest to farthest from the NPC. So distances[1] is the nearest player.

Thank you so much! Your script worked also. I’ve never thought on scripting through that way before. I know this may be off topic but I see that you are a youtuber, may I ask any advice on how to think like a programmer more? It just bothered me on how I can’t get myself to think the way many senior developers do. I’m more of an intermediate scripter, but is there a certain way/exercise to improve your ability to think solutions/blueprints of a script. Apologies if I’m being annoying.

I suppose the way of thinking comes with time. But the main takeaway here is that you should focus on learning something new, even if small, consistently over a long period of time. You’ll use these small pieces of knowledge to code things like your function.

Each time you encounter a new bug or want to implement a feature but don’t know how, get help like you did here or do research to solve it yourself. Don’t give up on it. Eventually, things you learn from others and through research will compound overtime.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.