Skip to content

Instantly share code, notes, and snippets.

@Elmuti
Created September 8, 2020 03:55
Show Gist options
  • Save Elmuti/a1b9dc2eede7aa52c7afb6ebed6a21bf to your computer and use it in GitHub Desktop.
Save Elmuti/a1b9dc2eede7aa52c7afb6ebed6a21bf to your computer and use it in GitHub Desktop.
function Pathfind(target, startPos, goalPos)
curStatus = "Pathfinding"
local abortPathfind = false
--GetNearestNode(position, returnBrick, dir, masterTable)
--GetNearestNodeVis(subject, position, visRange, returnBrick, dir, masterTable, ignore)
local startID = pathLib.GetNearestNodeVis(Root, startPos, losRange, false, map.Nodes, masterTable, {char, workspace.NPCs})
local goalID = NEW_GOAL_NODE or pathLib.GetNearestNodeVis(target, goalPos, losRange, false, map.Nodes, masterTable, {char, workspace.NPCs})
local path = pathLib.AStar(masterTable, startID, goalID)
NEW_GOAL_NODE = nil
spawn(function()
while true do
wait(2)
if target ~= nil then
if target.Parent ~= nil then
if target.Parent:FindFirstChild("Humanoid") then
local newGoal = target.Position
local goalnode = pathLib.GetNearestNode(goalPos, false, map.Nodes, masterTable)
if goalnode ~= goalID then
abortPathfind = true
NEW_GOAL_NODE = goalnode
end
end
end
end
end
end)
for nodeNum, node in pairs(path) do
local eta = npcLib.EstimatedPathTime(Root.Position, node.Position, Stats.WalkSpeed, 0.5)
local timeWalked = 0
while true do
if abortPathfind then
--warn("Adjusting new path")
return false
end
Root.Parent.Humanoid:MoveTo(node.Position)
local rotTarget
local nextNode = path[nodeNum + 1]
if nextNode == nil then
rotTarget = node.Position
else
rotTarget = nextNode.Position
end
CheckObstacles(node.Position)
RotateTowards(rotTarget)
local act = wait(1/20)
timeWalked = timeWalked + act
local newTarget = ChooseTarget()
--Reached node, Move to next node
if HasReachedDestination(node) then
--if node.Jump.Value then
--hum.Jump = true
--end
if timeouts > 0 then
timeouts = 0
end
break
end
--Target changed!
if newTarget ~= target and newTarget ~= nil then
--warn("-> Target changed from "..tostring(target).." to "..tostring(newTarget)..", aborting pathfind!")
return false
end
--Timed out! Return false, acquire new path
if timeWalked > eta then
--warn("-> Timed out!")
--char.Humanoid.Jump = true
timeouts = timeouts + 1
if timeouts >= maxTimeouts then
timeouts = 0
warn("NPC stuck at {"..tostring(Root.Position).."} !")
--char.Humanoid.Health = 0
break
end
return false
end
--Got line of sight on target, Stop finding the path and just walk there
local playerSeen = npcLib.LineOfSight(Root, newTarget, losRange, {script.Parent, workspace.Ignore, workspace.NPCs})
local cdist = (Root.Position - target.Position).magnitude
if playerSeen and cdist <= losRange then
--warn("-> Got line of sight on target, Stop pathfinding")
return false
end
end
end
return true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment