I want to create a pathfinding chase system that avoids obstacles and chases the player.
Currently, the pathfinding creates the correct path, but the enemy does not follow it. my current system only creates a new path if the player has moved a certain amount (so it’s not creating a new path every couple seconds). Right now i assume it’s skipping to the last waypoint (the player) each time, but if i add a Humanoid.MoveToFinished:Wait(), then it doesn’t stop and create a new path when the player moves as it has to finish the entire path before going on.
I’ve searched for solutions but none are quite the same as mine, and i’ve tried stuff like adding a MoveToFinished event but to no avail.
Script I’m currently using:
local PS = game:GetService("PathfindingService")
-- chaser info (parent should be chaser)
local rig = script.Parent
local Humanoid = rig:FindFirstChildOfClass("Humanoid")
local HRP = rig:FindFirstChild("HumanoidRootPart") or rig.PrimaryPart
local Chasing = false
-- this is how far the player needs to have had to move to make a new pathfind so its not wasting performance
local NewPathfindStudDifferenceRequirement = 2
local function Pathfind(startPos, endPos, callback)
-- change these to whatever
local Path = PS:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true
})
local success, errormsg = pcall(function()
Path:ComputeAsync(startPos, endPos)
end)
if success and Path.Status == Enum.PathStatus.Success then
callback(Path:GetWaypoints())
else
warn("Status: "..tostring(Path.Status))
warn("Success? "..success)
error("ERROR: "..errormsg)
end
end
local function Chase(Character:Model)
if not Character then return end
local TargetHum = Character:FindFirstChildOfClass("Humanoid")
local TargetHRP = Character:FindFirstChild("HumanoidRootPart") or Character.PrimaryPart
local LastTargetPosition
print("Beginning chase")
Chasing = true
while TargetHRP and TargetHum.Health > 0 do
print("Still alive")
-- if we have a last position, check the difference
if not LastTargetPosition or (TargetHRP.Position - LastTargetPosition).Magnitude > NewPathfindStudDifferenceRequirement then
print("new Pathfind, bc diff")
Pathfind(HRP.Position, TargetHRP.Position, function(Waypoints)
for i, Waypoint in Waypoints do
Humanoid:MoveTo(Waypoint.Position)
if Waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid.Jump = true
end
-- optional to visualize
local part = Instance.new("Part")
part.Anchored = true
part.CanCollide = false
part.Size = Vector3.new(0.5, 0.5, 0.5)
part.Material = Enum.Material.Neon
part.Color = Color3.fromRGB(255, 0, 0)
part.Position = Waypoint.Position
part.Parent = workspace
local Reached = false
local Connection
Connection = Humanoid.MoveToFinished:Connect(function()
Reached = true
Connection:Disconnect()
end)
end
end)
-- update last target position *after* pathfinding
LastTargetPosition = TargetHRP.Position
end
task.wait(0.15)
end
Chasing = false
warn("Finished Chasing")
end
-- wait to load
task.wait(1)
Chase(workspace.BNAN0TW)
