So I had recently made this pathfinding script after trying for a while to get it to a state where I felt It felt good enough for me to use for my NPCs, but from what I’ve seen of pathfinding it looks nothing compared to how I got it to work. It makes me think that this code would probably be inefficient and prone to being broken or probably too costly for the game to run constantly. Would this code be fine or would it need some reworking?
--// Variables \\--
local pathfindingService = game:GetService("PathfindingService")
local character = script.Parent
local humanoid = character:FindFirstChild("Humanoid")
local humRootPart = character:FindFirstChild("HumanoidRootPart")
local path = pathfindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 6,
AgentCanJump = true,
AgentCanClimb = true,
Costs = {
Water = math.huge
}
})
local endPos = workspace.EndPoint
local blockedConnection
local reachedConnection
local waypoints = {}
local waypointIndex = 1
humRootPart:SetNetworkOwner(nil)
--// Functions \\--
local function pathfind(goal)
local success, failed = pcall(function()
path:ComputeAsync(humRootPart.Position, goal.Position)
end)
if success and path.Status == Enum.PathStatus.Success then
print("Path Found!")
waypoints = path:GetWaypoints()
if #waypoints > 0 then
if #waypoints >= 3 and waypoints[3].Action == Enum.PathWaypointAction.Jump then
if humanoid.FloorMaterial ~= Enum.Material.Air then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
humanoid:MoveTo(waypoints[3].Position)
humanoid.MoveToFinished:Wait()
end
elseif #waypoints >= 3 and waypoints[3].Action == Enum.PathWaypointAction.Custom then
humanoid:MoveTo(waypoints[3].Position)
else
waypointIndex = 2
humanoid:MoveTo(waypoints[waypointIndex].Position)
end
print(waypoints[3])
end
else
warn("No path found! ".. tostring(failed))
end
end
--// Loops \\--
task.wait(4)
while task.wait() do
pathfind(endPos)
end