I’ve been trying to make an NPC that chases the player, but I came across this bug that I can’t fix.
When the NPC is within a 5-ish stud range of the player, they start to stutter, matching the player’s walking speed (12 studs/s) even though the NPC is faster (21 studs/s), does anybody know how to fix this?
Here’s the script:
local PathFindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local humanoid = script.Parent.Humanoid
local rootPart = script.Parent.HumanoidRootPart
pcall(function()
script.Parent.PrimaryPart:SetNetworkOwner(nil)
end)
local updateTime = 0.1
local moving = false
local newPath = PathFindingService:CreatePath(
{
AgentRadius = 2.1,
AgentHeight = 5,
AgentCanJump = false,
AgentCanClimb = false,
WaypointSpacing = 4
}
)
local currentTarget = nil
local function FindTarget()
local targetDistance = math.huge
local targetRootPart = nil
local targetPlayer = nil
for i, v in pairs(game.Players:GetPlayers()) do
if v.Character then
local playerHumanoid = v.Character:FindFirstChildOfClass("Humanoid")
local playerRootPart = playerHumanoid.RootPart
if playerHumanoid and playerRootPart then
local distance = (playerRootPart.Position - rootPart.Position).Magnitude
if distance > 0 and distance < targetDistance then
targetDistance = distance
targetRootPart = playerRootPart
end
end
end
end
return targetRootPart
end
local success, errorMsg
task.spawn(function()
local target = FindTarget()
if target then
success, errorMsg = pcall(function()
newPath:ComputeAsync(rootPart.Position, target.Position)
end)
end
end)
RunService.Heartbeat:Connect(function(delta)
if not moving then
moving = true
local target = FindTarget()
if target then
if success and newPath.Status == Enum.PathStatus.Success then
local waypoints = newPath:GetWaypoints()
if waypoints[2] then
currentTarget = waypoints[2].Position
task.spawn(function()
success, errorMsg = pcall(function()
newPath:ComputeAsync(waypoints[2].Position, target.Position)
end)
end)
else
currentTarget = nil
end
else
currentTarget = nil
end
else
currentTarget = nil
end
task.spawn(function()
if currentTarget then
humanoid:MoveTo(currentTarget)
else
success, errorMsg = pcall(function()
newPath:ComputeAsync(rootPart.Position, target.Position)
end)
humanoid:MoveTo(rootPart.Position)
end
end)
humanoid.MoveToFinished:Connect(function()
moving = false
end)
end
end)