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 5 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
5 years ago
Edited 5 years ago

First we need to find the nearest person.

Example:

01local vecPoint = workspace.NPC.Humanoid.Position
02local closestPlayer, smallestMagnitude = nil,math.huge
03 
04for _, player in pairs(game.Players:GetPlayers()) do
05     local distance = player:DistanceFromCharacter(vecPoint)
06     if distance < smallestMagnitude then
07          smallestMagnitude = distance
08          closestPlayer = player
09     end
10end

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

Script Example:

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

Final script:

01game.Players.PlayerAdded:connect(function(player)
02    player.CharacterAdded:connect(function(character)
03if character then
04local function movetonpc()
05local vecPoint = workspace.NPC.Humanoid.Position
06local closestPlayer, smallestMagnitude = nil,math.huge
07 
08for _, player in pairs(game.Players:GetPlayers()) do
09     local distance = player:DistanceFromCharacter(vecPoint)
10     if distance < smallestMagnitude then
11          smallestMagnitude = distance
12          closestPlayer = player
13 
14NPC.Humanoid:MoveTo(player.Character.Humanoid)
15     end
View all 23 lines...
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 — 5y
1
You are so right, I will edit that. raid6n 2196 — 5y
1
there we go raid6n 2196 — 5y
1
Thank you so much for the help! Au_Naturel -26 — 5y
0
-1 he asked for a pathfinding way, meaning using pathfinding service, you are using MoveTo nievadev 112 — 4y
Ad

Answer this question