Pathfinding Help

Hello all! I had a question on my pathfinding scripts. I am quite new to this service too, so forgive me if I made any mistakes. I was wondering why my pet was defying the laws of physics, and why are there about 50 different paths being made all at one time. I don’t know what I did wrong, since I am new and I’m just overall confused. I’ve studied the Roblox Documentation, yet nothing helped. Thank you.

local player = game.Players:FindFirstChild(script.Parent.PlayerName.Value)

local runService = game:GetService("RunService")

local pathfindingService = game:GetService("PathfindingService")

local path = pathfindingService:CreatePath()

local oldPos = nil

local createdPath = false

local numOfPaths = 0

local function calcPath()
	if not createdPath then
		path:ComputeAsync(script.Parent.HumanoidRootPart.Position, player.Character.HumanoidRootPart.Position)
	end

	if path.Status == Enum.PathStatus.Success then
		warn("got here")

		createdPath = true

		for i, v in pairs(path:GetWaypoints()) do
			path.Blocked:Connect(calcPath)

			warn(tostring(v.Position))

			local newPart = Instance.new("Part", game.Workspace)
			newPart.Anchored = true
			newPart.CanCollide = false
			newPart.Size = Vector3.new(1,1,1)
			newPart.Position = v.Position

			if v.Action == Enum.PathWaypointAction.Jump then
				script.Parent.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
			end

			script.Parent.Humanoid:MoveTo(v.Position)

			script.Parent.Humanoid.MoveToFinished:Wait()
		end
	end
end

runService.Heartbeat:Connect(function(step)
	if player.Character then

		local success, errorMessage = pcall(function()
			oldPos = (player.Character.HumanoidRootPart.CFrame).Position

			warn(tostring(oldPos).."=="..tostring((player.Character.HumanoidRootPart.CFrame).Position))

			if not createdPath then
				calcPath()

				numOfPaths = numOfPaths + 1

				print("NumOfPaths: "..numOfPaths + 1)

				createdPath = false
			end
		end)

		if errorMessage then
			warn("ERROR:"..errorMessage)

			game.ReplicatedStorage.SpawnFeterian:Invoke(player)
		end

	end
end)

The NPC must have all instances Anchored to false
I have the solution for you problem:

local player = game.Players:FindFirstChild(script.Parent.PlayerName.Value)
local path = game:GetService("PathfindingService"):CreatePath()

local function calcPath()
	repeat path:ComputeAsync(script.Parent.HumanoidRootPart.Position, player.Character.HumanoidRootPart.Position) until path.Status == Enum.PathStatus.Success
end

game:GetService("RunService").Heartbeat:Connect(function()
	calcPath()
	for i,v in pairs(path:GetWaypoints()) do
		path.Blocked:Connect(calcPath)
		script.Parent.Humanoid:MoveTo(v.Position)
	end
end)

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