AI continuously jumps instead of following path

I’ve been playing around with an AI for my game then I ran into this


My AI continuously jumps to try and get to me instead of following the nodes and jumping when needed. What have I done wrong?

local PFS

for i = 1, 1 do
	local me = game.ServerStorage.smart:Clone()
	me.Parent = workspace.NPCs
end

while true do

	for i, v in pairs(workspace.NPCs:GetChildren()) do
		
		PFS = game:GetService("PathfindingService"):FindPathAsync(v.HumanoidRootPart.Position, workspace:WaitForChild("Tom_atoes").HumanoidRootPart.Position)
	
		local Points = PFS:GetWaypoints()
		
		workspace.Points:ClearAllChildren()
		
		for i = 2, #Points do
			local lastWaypoint = Points[i - 1]
			local currentWaypoint = Points[i]
			
			local Point = Instance.new("Part", workspace.Points)
			Point.FormFactor = Enum.FormFactor.Symmetric
			Point.CanCollide = false
			Point.Size = Vector3.new(1, 1, 1)
			Point.Position = currentWaypoint.Position
			Point.Anchored = true
			
			Point.BrickColor = BrickColor.new("Really red")
			
			v.Humanoid:MoveTo(currentWaypoint.Position)
			
			local waypointType = currentWaypoint.Action	
			
			if waypointType == Enum.PathWaypointAction.Jump then

				v.Humanoid.Jump = true
		
			else
				
			end
			
		end
	
		wait(0.1)
	
	end
end
1 Like

It doesnt seem that the code waits until it finished doing its action
meaning its going to spam the jump action + try walking to the final point as its the last one in the loop
you need to make sure the npc gets to the point before going onto the next point

1 Like

How would I do this?

well i would personally change how you are doing this a bit

currently you are looping through every single waypoint and running their function at the same time
what you want is to do only one at a time, you probably want to use magnitude to find the distance between the npc and the point and when its close enough go to the next point etc instead of doing it all at once

EmeraldSlash (below) explains it pretty well

To wait for the humanoid to reach its target, you either wait for Humanoid.MoveToFinished:

Humanoid:MoveTo()
-- check for jumping and do everything else you need to do

Humanoid.MoveToFinished:Wait()

or you use a loop, checking to see if the character’s root part is within x (in this example, 3 studs) distance from the target:

Humanoid:MoveTo()
-- check for jumping and do everything else you need to do

repeat Distance = (Root.Position - TargetPosition).Magnitude until Distance < 3

I’ve tried using MoveToFinished before, it didn’t work for me, so I went with the latter solution – but I didn’t try very hard to debug it, so it may work for you.

The goal is to stop the for loop from continuing until the target position has been reached.

2 Likes