Pathfindingservice problem

I’m currently making an evil ai robot for a game. The robot needs to follow you where ever you go.
The moving script uses pathfindingservice to prevent the robot from getting stuck.
Problem is that the robot first completes the path to the original location of the path in stead of taking the fast way to the destination directly.
Here’s what I mean; https://gyazo.com/f5852e83949f5f1ce9e6f89eb670dd7e
If you don’t understand it, I made this; https://gyazo.com/11b37021e89d515328df809f36e5c7ee
This is my script:

local PathService = game:GetService("PathfindingService")


while wait() do
	local SmoothPath = PathService:ComputeSmoothPathAsync(workspace.Robot.HumanoidRootPart.Position,workspace.End.Position,512)
	local path = SmoothPath:GetPointCoordinates()
	
	workspace.Points:ClearAllChildren()
	
	for i=1,#path do
		local pos = path[i]
		local p = Instance.new("Part",workspace.Points)
		p.Anchored = true
		p.CanCollide = false
		p.Size = Vector3.new(1,1,1)
		p.Position = pos
		p.Color = Color3.fromRGB(255,0,0)
		workspace.Robot.Humanoid:MoveTo(p.Position)
		workspace.Robot.Humanoid.MoveToFinished:Wait()
	end
end

Can anyone help me fix this?

1 Like

im not entirely sure but if you replace the .movetofinished with just a wait() it should fix it.

That causes the robot to be stuck at obstacles. https://gyazo.com/83aad2b4cad973008c2c65db133c2b52

Can you post the script using the ``` infront and behind of the script? It makes it easier to look at.

Okay, edited the post so it’s cleaner now.

Try calculating a new path every so often, instead of when it reaches its target.

1 Like

The script pretty much calculates the route, and then moves to the position. By using the for loop to move the AI, it can’t do anything else (including calculating a new route) until the AI finishes the for loop (finishes the path). To prevent this, i would recommend checking if the player has moved each time the for loop runs, and recalculate the route if it has.

Try using ‘break’ to exit the for loop if the player has moved.

local PathService = game:GetService("PathfindingService")


while wait() do
	local SmoothPath = PathService:ComputeSmoothPathAsync(workspace.Robot.HumanoidRootPart.Position,workspace.End.Position,512)
	local path = SmoothPath:GetPointCoordinates()
	
	workspace.Points:ClearAllChildren()
	
	for i=1,#path do

        if player has moved then
            break
        end

		local pos = path[i]
		local p = Instance.new("Part",workspace.Points)
		p.Anchored = true
		p.CanCollide = false
		p.Size = Vector3.new(1,1,1)
		p.Position = pos
		p.Color = Color3.fromRGB(255,0,0)
		workspace.Robot.Humanoid:MoveTo(p.Position)
		workspace.Robot.Humanoid.MoveToFinished:Wait()
	end
end

Remember to check if the player has moved before the ‘if’ statement but still inside the for loop.