I recently made a code for an ai to find the closest player, walk to that player if it is under a certain distance, and pathfinder to that player so it doesn’t walk into walls.
Specifics
- There should not be any jumping events within the created path
Problems
- Does not even pathfind
- after around 10 seconds the nPC just stops
Broken Code:
local closestPlayer = nil
local closestDistance = 110
local NPC = script.Parent
local players = game:GetService("Players")
local pathfindingService = game:GetService("PathfindingService")
local lastPos = nil
function getClosestPlayer()
closestPlayer = nil
for _, player in pairs(players:GetPlayers()) do
if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
local playerPosition = player.Character.HumanoidRootPart.Position
local distance = (playerPosition - NPC.HumanoidRootPart.Position).magnitude
if distance < closestDistance then
closestPlayer = game.Workspace.Players:FindFirstChild(player.Name)
closestDistance = distance
end
end
end
return closestPlayer
end
local pathParams = {
AgentHeight = 5,
AgentRadius = 3,
AgentCanJump = false,
}
local function getPath(destination)
local path = pathfindingService:CreatePath(pathParams)
path:ComputeAsync(NPC.PrimaryPart.Position, destination.Position)
return path
end
function walkToPlayer()
local closestPlayer = getClosestPlayer()
if closestPlayer ~= nil then
local path = getPath(closestPlayer.PrimaryPart)
if path.Status == Enum.PathStatus.Success then
print("path.Status = Success")
for i, waypoint in pairs(path:GetWaypoints()) do
path.Blocked:Connect(function()
path:Destroy()
end)
local target = closestPlayer
if target and target.Humanoid.Health > 0 then
lastPos = target.HumanoidRootPart.Position
NPC.Hum:MoveTo(target.HumanoidRootPart.Position)
break
else
if waypoint.Action == Enum.PathWaypointAction.Jump then
NPC.Hum:ChangeState(Enum.HumanoidStateType.Jumping)
end
if lastPos then
NPC.Hum:MoveTo(lastPos)
NPC.Hum.MoveToFinished:Wait()
lastPos = nil
break
else
NPC.Hum:MoveTo(waypoint.Position)
NPC.Hum.MoveToFinished:Wait()
end
end
end
else
return
end
end
end
while true do
walkToPlayer()
wait()
end