I’m currently working on an AI pathfinding chase module, and it’s been working great so far. There’s only one issue, and it’s that the NPC has to complete it’s fully generated path, before starting a new one. This means that it barely chases the player, and just sort of lags behind them. I’ve already tried removing the Humanoid.MoveToFinished:Wait(), but when I remove that, the pathfinding doesn’t work very well at all. Any help?
Module:
local module = {}
function module:FindNearestTarget(Killer, Range)
local Characters = {}
local Target
for i, v in pairs(game.Players:GetPlayers()) do
local Character = v.Character or v.CharacterAdded:Wait()
local pos1 = Killer.HumanoidRootPart.Position
local pos2 = Character.HumanoidRootPart.Position
local Magnitude = (pos1-pos2).Magnitude
if Magnitude <= Range then
table.insert(Characters, Character)
end
table.sort(Characters, function (a, b) return (b.Position - pos1).magnitude > (a.Position - pos1).magnitude
end)
Target = Characters[1].HumanoidRootPart
print(Target.Parent.Name)
return Target.Position
end
end
function module:Pathfind(Killer, Destination)
local PathfindingService = game:GetService("PathfindingService")
local Debris = game:GetService("Debris")
local Humanoid = Killer:WaitForChild("Killer")
local RootPart = Killer:WaitForChild("HumanoidRootPart")
local Path = PathfindingService:CreatePath()
local GenPoint = nil
local PointArray = {}
RootPart:SetNetworkOwner(nil)
Path:ComputeAsync(RootPart.Position, Destination)
local Waypoints = Path:GetWaypoints()
for i, v in ipairs(Waypoints) do
GenPoint = v
table.insert(PointArray, GenPoint)
local Point = Instance.new("Part")
Point.Anchored = true
Point.Shape = "Ball"
Point.Size = Vector3.one*0.5
Point.Position = v.Position + Vector3.new(0,2,0)
Point.CanCollide = false
Debris:AddItem(Point, 5)
Point.Parent = workspace
Point.Name = "Point"..tostring(i)
end
for i2, v2 in ipairs(PointArray) do
if v2.Action == Enum.PathWaypointAction.Jump then
Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
Humanoid:MoveTo(v2.Position)
Humanoid.MoveToFinished:Wait()
task.wait()
end
end
return module
Script in NPC:
task.wait()
local PathfindModule = require(game.ReplicatedStorage:WaitForChild("PathfindingModule"))
while task.wait() do
local Destination = PathfindModule:FindNearestTarget(script.Parent, 1000)
PathfindModule:Pathfind(script.Parent, Destination)
end