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 make a pathfinding NPC that will follow a player smartly?

So what I want to do is make a smart killing npc that can go through doors and follow the player without jumping into a wall for the whole game.

I have everything down except how to make the npc focus on a player not a block or another NPC

1 answer

✓ Accepted answer

First we need to find the nearest person.

Example:

local vecPoint = workspace.NPC.Humanoid.Position
local closestPlayer, smallestMagnitude = nil,math.huge

for _, player in pairs(game.Players:GetPlayers()) do
     local distance = player:DistanceFromCharacter(vecPoint)
     if distance < smallestMagnitude then
          smallestMagnitude = distance
          closestPlayer = player
     end
end

Boom, we did it. Now we want the player to go the Player.

Script Example:

NPC.Humanoid:MoveTo(player.Character.Humanoid)

Final script:

game.Players.PlayerAdded:connect(function(player)
	player.CharacterAdded:connect(function(character)
if character then
local function movetonpc()
local vecPoint = workspace.NPC.Humanoid.Position
local closestPlayer, smallestMagnitude = nil,math.huge

for _, player in pairs(game.Players:GetPlayers()) do
     local distance = player:DistanceFromCharacter(vecPoint)
     if distance < smallestMagnitude then
          smallestMagnitude = distance
          closestPlayer = player

NPC.Humanoid:MoveTo(player.Character.Humanoid)
     end
end
end
while wait(.01) do
 movetonpc()
end
end
end)
end)

5 comments

2

You forgot to check if the player has a character at all! “It returns 0 if the player has no Player.Character”, meaning the smallest magnitude is of the player who has no character

1

You are so right, I will edit that.

1

there we go

1

Thank you so much for the help!

0

-1 he asked for a pathfinding way, meaning using pathfinding service, you are using MoveTo

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