Ive been trying to fix this pathfinding code for the past 5 weeks and have re-written the code 6 times, yet I cant seem to get it to work. Here’s what its looking like:
As you can see, when it is wandering, it works absolutely flawlessly. However, whenever I become the target, this happens:
As the red spheres indicate, it is calculating the path fine still, but it wont follow it, except rarely for a really short period of time, really slowly.
Here’s my code:
-- main functions
local function followPath()
pathIsRunning = true
while true do
if ind >= #waypoints - 1 then
onTargetReached()
local w = waypoints
repeat wait() until w ~= waypoints
continue
end
if waypoints[ind].Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
humanoid:MoveTo(waypoints[ind].Position)
ind += 1
print(ind)
humanoid.MoveToFinished:Wait()
end
end
local function calcPath(targetPos: Vector3): nil
local success, errorm = pcall(function()
path:ComputeAsync(ghostRoot.Position, targetPos)
end)
if success then
waypoints = path:GetWaypoints()
updatePoints()
if #waypoints <= 2 then
onTargetReached()
return
end
local bestWaypoint: number = 1
local bestDist: number = distSquared(waypoints[1].Position, ghostRoot.Position)
local secondBestWaypoint: number = 2
local secondBestDist: number = distSquared(waypoints[2].Position, ghostRoot.Position)
if secondBestDist < bestDist then
local temp = {bestWaypoint, bestDist}
bestWaypoint = secondBestWaypoint
bestDist = secondBestDist
secondBestWaypoint = temp[1]
secondBestDist = temp[2]
end
for i = 3, #waypoints, 1 do
local wp = waypoints[i]
local dist: number = distSquared(wp.Position, ghostRoot.Position)
if dist < bestDist then
secondBestDist = bestDist
secondBestWaypoint = bestWaypoint
bestDist = dist
bestWaypoint = i
elseif dist < secondBestDist then
secondBestDist = dist
secondBestWaypoint = i
end
end
ind = math.max(secondBestWaypoint, bestWaypoint)
if not pathIsRunning then
followPath()
end
else
warn("Error while computing path: "..errorm)
lastPathTarget = nil
end
end
I also have some code that will run calcPath every 0.2 seconds with a new place to go to. I will send this if requested. followPath is only called once as the pathIsRunning flag suggests. I know its not lag because here are the script analytics taken from the developer console in game:
I have tried spacing out the waypoints further, increasing the delay between path calculations, but nothing works. Does anyone have any idea as to what is going wrong?
Thanks for any help!