NPC only moves once in pathfinding script

I’m trying to make a pathfinding script that allows the NPC to move to the vector3 position given in a target variable. This target variable will change if the NPC hears, sees, or is simply patrolling around the area. I have other functions not shown that change this variable. The issue is that the NPC only moves once and doesn’t move again.

Some things to know:
1.The target variable works as intended
2.The waypoint table is changing when the NPC targets a certain position (it works as intended)
3. Idlemoving is a variable I used to identify if the NPC is moving passively when idle, just ignore it
4. Moveactive is the variable I used when trying to fix this situation on my own, and obviously it is a failed attempt

Thanks.

local function startmovement (wp)
	print(wp)
	if moveactive then moveactive = false end
	if idle and not idlemoving then idlemoving = true end
	activect = coroutine.running()
		for i, v in pairs (wp) do
		if moveactive then
			moveactive = false
				break end
		moveactive = true	
		if activect ~= coroutine.running() then return end
		subject:MoveTo(v.Position)
		if v.Action == Enum.PathWaypointAction.Jump then
			subject.Jump = true
		end
		
		if idle then
			idlemoving = false
			if currentphase == "investigationphase" then
				currentphase = "patrolphase"	
			end
		end
	end	
	subject.MoveToFinished:Wait()
	end
	

local function update()
	if target then	
		path:ComputeAsync(subject.Parent.HumanoidRootPart.Position, target)
		local wp = path:GetWaypoints()
		table.remove(wp, 1)
		coroutine.wrap(startmovement)(wp)
	end	
end```
1 Like

You put subject.MoveToFinished:Wait() on the wrong line. It should be above the end above it. I’m sure yk what it does because of this (tries going to all of them at the save time, ends up going to one), instead it should be inside the pair so it’ll wait after it’s done, then go to the next waypoint and repeat the process which will yield until the entire movement’s done. Prob just a formatting mistake.

2 Likes

It moves more than once now, so I will mark this topic as solved. However, the movement still doesn’t work properly so I don’t recommend using this as a resource.

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