NPC keeps making short stops

Heya Everyone!!

I’m making a 2013 ROBLOX style game and I’m working on the zombie AI. I’m reusing from a scrapped project to make the zombies constantly move towards the player without having to wait until it directly goes to the players position. The issue is that, as the title says, it keeps pausing every short while.

--//This is the entire pathfinding script.
function BASE_ZOMBIE_MODULE:ChaseTarget(Target)
	
	local NewPath = PathfindingService:CreatePath()
	NewPath:ComputeAsync(self.Entity.PrimaryPart.Position, Target.PrimaryPart.Position)
	if NewPath.Status == Enum.PathStatus.Success then
		local Waypoints = NewPath:GetWaypoints()
		
		for i, Waypoint in ipairs(Waypoints) do
			if i <= 2 then continue end
			if Waypoints[4] then
				self.Humanoid:MoveTo(Waypoints[4].Position)
				
				local TimeOut = self.Humanoid.MoveToFinished:Wait()
				if not TimeOut then
					warn("NPC got stuck or took too long. Repathfinding")
					self:ChaseTarget()
				end
			end
		end
		
	end
2 Likes

from the looks of it it’s only ever moving to the 4th waypoint. What you should be doing instead is:

local Humanoid = self.Humanoid
-- should probably store this variable at the top since you use it frequently

local Waypoints = NewPath:GetWaypoints()
Waypoints[1] = nil -- removes the first way points since it's just the Entity's Position

for _, PathPoint in Waypoints do
	Humanoid:MoveTo(Waypoint.Position)

	if not Humanoid.MoveToFinished:Wait() then -- don't need to store it as a variable
		warn("NPC got stuck")
		self:ChaseTarget()
	end
end

1 Like

I tried that and it fixes the issue of the NPC stopping but another problem arises which the NPC only goes to where the player was originally at before updating the path.

Well to make it follow the player, you’re gonna have to change the NPC’s path constantly, usually around 0.25 seconds works for me. To do this without it breaking a whole bunch you’ll need to know how to use tasks (task.defer(), task.cancel()) and also a way to detect when the NPC reaches its destination, preferably using a Signal module of some sort. While I could tell you how to do it, it will get complicated. So to save you a lot of time I suggest you use NoobPath. It basically does everything I mentioned. If you don’t want to use an outside source. I don’t mind teaching you how, just, be prepared to have to do a lot of debugging and testing.

I really don’t want to use a module script since I want to learn how to pathfind correctly without having to encounter these issues, so teach me how if that’s okay with you.

Only use pathfinding when the player is not in view. Use pathfinding when the player isn’t in view- and as soon as it sees the player, you can stop pathfinding and just walk to the player constantly until they aren’t in view again.

It’s stopping because I think you make paths frequently, or maybe your calculations or the step distance between waypoints is too short or high.

1 Like

Sorry for the late replay went to go eat.

[Edit] Me getting food did not do anything.. This post was just stupidly long

Anyway Task library video:

Signal module:
Just wanna say, we aren’t making our Signal Module and will be using an outside source. Why? Well cause I don’t know how to make one. This is coming from someone who’s also pretty advanced at scripting (at least I like to think I am) and also doesn’t like using outside sources. So to save me and you trouble we’ll just use GoodSignal

You’ll have to copy and paste the GoodSignal source script from the github into a module also.
GoodSignal Post, the source script github link is the first link in his post.

GoodSignal video showcase:

Ok cool hopefully you’ve watched the videos and know a bit how they work now. On to scripting.

The way I made my NPC walking system was using an OOP/class system. Anyway the starting class or whatever:

local PathService = game:GetService("PathfindingService")
local GoodSignal = require(script.GoodSignal)

local module = {}

function module.new(NPC)
	local newThing = {
		HumRoot = NPC.HumanoidRootPart,
		Humanoid = NPC.Humanoid,
		WalkEnd = GoodSignal.new(),
		WalkTask = nil,
	}
	setmetatable(newThing,{__index = module})
	return newThing
end

return module

HumRoot and Humanoid are as they are named, the humanoidrootpart and Humanoid of the NPC.

WalkEnd will be used to detect when the NPC either finishes walking to its destination or if the NPC got stuck somewhere and the walking loop ends. It will fire true if and when the NPC reaches its destination and will fire false if it ever fails to reach its destination.

WalkTask will be a thread/task we make when we make the NPC walk to a position. This variable will be important for when we want to stop the NPC from walking mid way into his path so it can walk a new path.

On to making NPC walk:

function module:Walk(EndPos:Vector3)
	if self.WalkTask then
		task.cancel(self.WalkTask)
		self.WalkEnd:Fire(false)
	end
	-- other stuff will be added, explaining step by step

This will cancel any WalkTask currently running so that we can make the NPC follow a new path

Next code:

	-- other stuff
	local PathBrain = PathService:CreatePath()
	PathBrain:ComputeAsync(self.HumRoot.Position,EndPos)
	
	if PathBrain.Status == Enum.PathStatus.Success then
		self.WalkTask = task.defer(function() -- Sets WalkTask so we can cancel it later
			local Humanoid:Humanoid = self.Humanoid
			local Waypoints = PathBrain:GetWaypoints()
			Waypoints[1] = nil

			for _,PathPoint:PathWaypoint in Waypoints do
				if PathPoint.Action == Enum.PathWaypointAction.Jump then
					Humanoid.Jump = true
				end
				Humanoid:MoveTo(PathPoint.Position)
				if not Humanoid.MoveToFinished:Wait() then
					self.WalkTask = nil
					self.WalkEnd:Fire(false)
					return
				end
			end
			
			self.WalkTask = nil
			self.WalkEnd:Fire(true)
		end)
	end
end
-- Walk function end

It’s basically the same code above with a few differences. It sets the entire thing in a task.defer() so that it doesn’t pause the script and so that we can call WalkEnd:Wait() before the script finishes. As using a task.spawn() will sometimes call the WalkEnd:Fire() too early thus pretty much breaking the script.

There’s also a if PathPoint.Action == Jump then to check if the NPC has to jump to reach to the next waypoint (Humanoid.Jump = true makes the NPC jump).

You may also notice there’s self.WalkTask = nil and self.WalkEnd:Fire() at the end. This is because the thread/task has completed basically. We set self.WalkTask to nil whenever the thread/task is completed so we can avoid closing an already closed thread, which will result with an error.

Entire Walk Function
function module:Walk(EndPos:Vector3)
	if self.WalkTask then
		task.cancel(self.WalkTask)
		self.WalkEnd:Fire(false)
	end
	local PathBrain = PathService:CreatePath()
	PathBrain:ComputeAsync(self.HumRoot.Position,EndPos)
	
	if PathBrain.Status == Enum.PathStatus.Success then
		self.WalkTask = task.defer(function() -- Sets WalkTask so we can cancel it later
			local Humanoid:Humanoid = self.Humanoid
			local Waypoints = PathBrain:GetWaypoints()
			Waypoints[1] = nil

			for _,PathPoint:PathWaypoint in Waypoints do
				if PathPoint.Action == Enum.PathWaypointAction.Jump then
					Humanoid.Jump = true
				end
				Humanoid:MoveTo(PathPoint.Position)
				if not Humanoid.MoveToFinished:Wait() then
					self.WalkTask = nil
					self.WalkEnd:Fire(false)
					return
				end
			end
			
			self.WalkTask = nil
			self.WalkEnd:Fire(true)
		end)
	end
end
Example Usage
local newAi = AiClass.new()
-- assume we've set up the NPC correctly and what not
newAi:Walk(Endpos_Here) -- since we used task.defer() the script won't pause

if newAi.WalkEnd:Wait() then -- WalkEnd will either be true or false, this will also pause script
	print("Npc Reached end pos") -- WalkEnd was true
else
	print("Npc didn't reach end pos") -- WalkEnd was false
end
print("End")

Now we’ll need a way to stop the NPC from walking mid way into his path.

function module:ForceEndPath()
	if self.WalkTask then
		task.cancel(self.WalkTask)
		self.WalkTask = nil
	end
	self.WalkEnd:Fire(false)
end

When we run this it’ll check if there’s currently a WalkTask thread/task and cancel it, basically stopping it from running. After that, it sets it to nil so the script knows there’s currently no running walk loop function.
Example:

local newAi = AiClass.new()
-- assume we've set up the NPC correctly and what not
newAi:Walk(Endpos_Here) -- since we used task.defer() the script won't pause

task.wait(2)
newAi:ForceEndPath() -- will stop the NPC from walking after 2 seconds, if it's still walking.

That’s pretty much the end of the module for the walking:

Entire Module
local PathService = game:GetService("PathfindingService")
local GoodSignal = require(script.GoodSignal)

local module = {}

function module.new(NPC)
	local newThing = {
		HumRoot = NPC.HumanoidRootPart,
		Humanoid = NPC.Humanoid,
		WalkEnd = GoodSignal.new(),
		WalkTask = nil,
	}
	setmetatable(newThing,{__index = module})
	return newThing
end

function module:ForceEndPath()
	if self.WalkTask then
		task.cancel(self.WalkTask)
		self.WalkTask = nil
	end
	self.WalkEnd:Fire(false)
end

function module:Walk(EndPos:Vector3)
	if self.WalkTask then
		task.cancel(self.WalkTask)
		self.WalkEnd:Fire(false)
	end
	local PathBrain = PathService:CreatePath()
	PathBrain:ComputeAsync(self.HumRoot.Position,EndPos)
	
	if PathBrain.Status == Enum.PathStatus.Success then
		self.WalkTask = task.defer(function() -- Sets WalkTask so we can cancel it later
			local Humanoid:Humanoid = self.Humanoid
			local Waypoints = PathBrain:GetWaypoints()
			Waypoints[1] = nil

			for _,PathPoint:PathWaypoint in Waypoints do
				if PathPoint.Action == Enum.PathWaypointAction.Jump then
					Humanoid.Jump = true
				end
				Humanoid:MoveTo(PathPoint.Position)
				if not Humanoid.MoveToFinished:Wait() then
					self.WalkTask = nil
					self.WalkEnd:Fire(false)
					return
				end
			end
			
			self.WalkTask = nil
			self.WalkEnd:Fire(true)
		end)
	end
end

return module

So once you have those functions down you can easily just constantly call this every .25 seconds, assuming you have the target and all that stuff

local newAi = AiClass.new()
local Target = Model

while true do
	newAi:Walk(Target.Position)
	task.wait(.25)
end
2 Likes

movetofinished:Wait() causes short stops or delay replace it with once or your calling waypoints[4] instead of current waypoint

this script I made kinda works try it

local PathFindingManager = {}

local pathfindingservice = game:GetService("PathfindingService")
function PathFindingManager.CreatePath(rig:Model,targetposition:Part)
	local humanoid = rig:FindFirstChildOfClass("Humanoid")
	local path = pathfindingservice:CreatePath({
		AgentCanJump = true,
		AgentCanClimb = true,
		
		Costs = {
			Neon = math.huge
		}
	})
	local success, errorMessage = pcall(function()
		rig.PrimaryPart:SetNetworkOwner(nil)
		path:ComputeAsync(rig.PrimaryPart.Position,targetposition.Position)
	end)
	if success and Enum.PathStatus.Success then
		local waypoints = path:GetWaypoints()
		local Index = 1
		
		local function MoveNext()
			if Index > #waypoints then
				return
			end
			local waypoint:PathWaypoint = waypoints[Index]
			
			if waypoint.Action == Enum.PathWaypointAction.Jump then
				humanoid.Jump = true
			end
			
			humanoid:MoveTo(waypoint.Position)
			
			humanoid.MoveToFinished:Once(function(reached)
				if reached then
					Index += 1
					MoveNext()
				else
					print("failed")
					PathFindingManager.CreatePath(rig, targetposition)
				end
			end)
		end
		MoveNext()
	else
		humanoid:MoveTo(targetposition.Position)
	end
end

return PathFindingManager

add a number placeholder variable that is responsible for the waypoints generated In order, connect movetofinished with once then add index by 1 then call the function again or just read the script