I’m trying to make a NPC which’ll follow the nearest player but mine stops while following and it’s very easy to get rid of its’ following. That was the best I could do and there aren’t really good tutorials for this so I need help.
-- Services
local pathfindingService = game:GetService("PathfindingService")
-- Config
local aggroDist = 10
-- Variables
local character = script.Parent.Parent
local humanoid = character:WaitForChild("Humanoid")
local HumanRoot = character:WaitForChild("HumanoidRootPart")
-- Tool
local tool = character.ClassicSword
-- Functions
local function createPath(hrp)
local path = pathfindingService:CreatePath()
path:ComputeAsync(hrp.Position,HumanRoot.Position)
-- Waypoints
local waypoints = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success then
for _, waypoint in pairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
path.Blocked:Connect(function()
print("Path blocked")
local newpath = pathfindingService:CreatePath()
newpath:ComputeAsync(character:FindFirstChild("HumanoidRootPart"), hrp.Position)
waypoints = path:GetWaypoints()
end)
end
-- Ray
while wait(0.5) do
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {
character
}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist
rayParams.IgnoreWater = false
local result = workspace:Raycast(HumanRoot.Position, character.Head.CFrame.LookVector*aggroDist, rayParams)
if result then
if result.Instance:IsA("BasePart") then
if result.Instance.Parent:FindFirstChild("Humanoid") then
trackingChar = result.Instance.Parent
local magnitude = math.abs((HumanRoot.Position - result.Position).Magnitude)
if magnitude < aggroDist then
coroutine.wrap(createPath)(result.Instance.Parent:FindFirstChild("HumanoidRootPart"))
end
end
end
end
end