Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make a pathfinding NPC that will follow a player smartly?

Asked by 4 years ago

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

Log in to vote
0
Answered by
raid6n 2196 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

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)
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 ankurbohra 681 — 4y
1
You are so right, I will edit that. raid6n 2196 — 4y
1
there we go raid6n 2196 — 4y
1
Thank you so much for the help! Au_Naturel -26 — 4y
0
-1 he asked for a pathfinding way, meaning using pathfinding service, you are using MoveTo nievadev 112 — 3y
Ad

Answer this question