How to make my pathfinding npc smarter?

Something like this maybe would work:

local pfs = game:GetService("PathfindingService")
local wps = {}
local path = pfs:CreatePath({
	AgentCanClimb = true,
})
local wpIdx = 1
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local hrp = char:WaitForChild("HumanoidRootPart")

local humrp = char.HumanoidRootPart

local db = false
local moved = false
local target

local function findTarget()
	local players = game.Players:GetPlayers()
	local MaxDistance = 9999999999
	local nearestTarget

	for i,v in pairs(players) do
		if (v.Character) then
			local target = v.Character
			local distance = (humrp.Position - target.HumanoidRootPart.Position).Magnitude

			if (distance < MaxDistance) then
				nearestTarget = target
				MaxDistance = distance
			end
		end
	end

	return nearestTarget
end

local function followPath()
	db = true
	local goal = target.Torso
	path:ComputeAsync(hrp.Position, goal.Position)
	wps = {}
	if path.Status == Enum.PathStatus.Success then
		wps = path:GetWaypoints()
		for i,v in pairs(wps) do
			wpIdx += 1
			if i < #wps then
				if wps[i].Action == Enum.PathWaypointAction.Jump then
					hum.Jump = true
				end
				hum:MoveTo(wps[i].Position)
				hum.MoveToFinished:Wait()
				if moved then
					followPath()
					moved = false
					print("repositioning")
					break
				end
			else
				db = false
			end
		end
	end
end

path.Blocked:Connect(function(blockedWpIDX)
	if blockedWpIDX > wpIdx then
		target = findTarget(script.Parent.HumanoidRootPart)
		if target ~= nil then
			followPath(target.Torso)
		end
	end
end)

game:GetService("RunService").Heartbeat:Connect(function(deltatime)
	target = findTarget(script.Parent.HumanoidRootPart)
	if target ~= nil and db == false then
		followPath(target.Torso)
	end
end)

repeat task.wait(0.5) until target

target.Head:GetPropertyChangedSignal("CFrame"):Connect(function()
	print("moved")
	moved = true
end)

It’s kind of hard to get it to catch up because I don’t think there’s a way to get more waypoints for it to check more often. But what I would recommend you do it PLEASE, learn the basics before trying to code something complex. Learn from the ground up and you I can’t even explain how much better of a scripter you would be!

1 Like

i’ll keep that in mind, thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.