Ok so basically Ive used several sources and codes from different places, edited them to fit what I need, and Ive got a script that kinda works! Im working on a Pathfinding AI for my SCP Foundation that tracks the nearest player within a certain distance,
The issue is that if the player moves but is still within the AI’s Field of Vision (100 Studs in this case) the path wont update, I removed the section of code that prevented the AI from remaking a path if the target is the same, it tries to update its path, but instead it appears the AI is getting confused and it ends up jumping and spinning in circles.
I have yet to come up with any solutions, but I will leave my code below, as I am not one to hide my code, especially after the amount of help I have already gotten.
CODE
local PathfindingService = game:GetService("PathfindingService")
local SCPAI = script.Parent
local humanoid = SCPAI.Humanoid
local destination = nil
local lastdestination = nil
local destinationlastpos = nil
local path = PathfindingService:CreatePath()
local waypoints
local currentWaypointIndex
local function GetClosest()
local aiHrp = SCPAI.HumanoidRootPart
local closestDist = 100
local closestObj = nil
local closestPos = nil
for i,v in pairs(game.Players:GetPlayers()) do
local char = v.Character or v.CharacterAdded:Wait()
local hrp = char.HumanoidRootPart
local dist = (aiHrp.Position-hrp.Position).Magnitude
if dist <= closestDist then
closestDist = dist
closestObj = char
closestPos = closestObj.HumanoidRootPart.Position
end
end
return closestObj, closestPos
end
local function followPath(destinationObject)
path:ComputeAsync(SCPAI.HumanoidRootPart.Position, destinationObject)
waypoints = {}
waypoints = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
currentWaypointIndex = 1
humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
else
humanoid:MoveTo(SCPAI.HumanoidRootPart.Position)
end
end
local function onWaypointReached(reached)
if reached and currentWaypointIndex <= #waypoints then
if waypoints[currentWaypointIndex].Action == Enum.PathWaypointAction.Walk then
humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
elseif waypoints[currentWaypointIndex].Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
end
currentWaypointIndex = currentWaypointIndex + 1
else
destination = nil
end
end
local function onPathBlocked(blockedWaypointIndex)
if blockedWaypointIndex > currentWaypointIndex then
followPath(destination)
end
end
while true do
wait()
destination, destinationlastpos = GetClosest()
if game.Players:GetPlayerFromCharacter(destination) then
lastdestination = destination
followPath(destinationlastpos)
path.Blocked:Connect(onPathBlocked)
humanoid.MoveToFinished:Wait()
humanoid.MoveToFinished:Connect(onWaypointReached)
end
if not game.Players:GetPlayerFromCharacter(destination) then
destination = nil
lastdestination = nil
end
end