I modified a pathfinding script from a video I watched to make it go to a player instead of a block.
The npc kind of spazzes out while moving toward the player somewhat, and eventually gets to its target, but moves, idles, moves, idles, moves, idles, so on and so forth.
This is the code.
local pfs = game:GetService("PathfindingService")
local wps = {}
local path = pfs:CreatePath()
local wpIdx = 1
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local hrp = char:WaitForChild("HumanoidRootPart")
local treasure
local plrs = game:GetService("Players")
local function followPath(goal)
print("follow started")
for i, plr in pairs(plrs:GetChildren()) do
local targethrp
print("starting loop")
local ch = plr.Character
print("character defined")
if ch then
print("character is there")
targethrp = ch:FindFirstChild("HumanoidRootPart")
if targethrp then
local d = (hrp.Position - targethrp.Position).Magnitude
if d < 9000 then
treasure = targethrp
print(treasure.Name)
print(targethrp.Name)
--create and set up path
path:ComputeAsync(hrp.Position, targethrp.CFrame.Position)
wps = {}
if path.Status == Enum.PathStatus.Success then
wps = path:GetWaypoints()
wpIdx = 1
hum:MoveTo(wps[wpIdx].Position)
else
print("No path found")
end
end
end
end
end
end
while task.wait(0.1) do
hum.MoveToFinished:Connect(function(reached)
if reached and wpIdx < #wps then
wpIdx += 1
if wps[wpIdx].Action == Enum.PathWaypointAction.Jump then
hum.Jump = true
end
hum:MoveTo(wps[wpIdx].Position)
end
end)
path.Blocked:Connect(function(blockedWpIdx)
if blockedWpIdx > wpIdx then
followPath(treasure)
end
end)
followPath(treasure)
end