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

How do I make a NPC follow the nearest player?

So I am trying to make a game and need to have a cube follow and attack a player but I have tried too many times to count. Can anyone help me out?

1 comment

0

try it yourself and then when you have some code come back and ask for help with your code

1 answer

The following script provides the closest player once you input the origin. You can put this in a module script for easy access. Or a function, whatever works.

local players = game:GetService('Players')

function module.FindNearestPlayer (origin)
	-- so how this is going to work is it is going to cycle through
	-- all the players position
	-- once it finds the best one SO FAR it saves it to a variable.
	-- then it just keeps going comparing each position to the best one.
	-- then the best one is returned after everything is iterated.
	
	
	local bestChoice = nil 
	local bestPos = nil
	
	for i, player in pairs(players:GetPlayers()) do
		local char = player.Character or player.CharacterAdded:Wait()
		local pos = char.PrimaryPart.Position
		
		if bestChoice ~= nil then
			if (origin - pos).Magnitude < (origin - bestPos).Magnitude then
				bestChoice = player
				bestPos = pos
			end 
		else
			bestChoice = player
			bestPos = pos
		end
	end
	
	return bestChoice
end

Just call the module with the origin and you should get the nearest player.

The npc moving part you will have to do mostly yourself, this is because I have no clue how your game runs or works. But I assume you will do stuff with humanoid:MoveTo() so you can start there.

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