Pathfinding NPC stutters when getting close to player after changing walkspeed

External Media

In the video above, after my player uses their speed ability, the NPCs slow down and stutter massively. They become easily avoidable and are very, VERY slow.

Pathfinding Code:

local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")

local NPC = script.Parent
local Humanoid = NPC:WaitForChild("Humanoid")
local HRP = Humanoid.RootPart

local Values = NPC:WaitForChild("Values")
local Target = Values:WaitForChild("Target")

local AttackDistance = 1

function PathfindCompute()
	local PathfindConnection

	PathfindConnection = RunService.Stepped:Connect(function()
		if not Humanoid or not HRP or Humanoid.Health <= 0 then
			PathfindConnection:Disconnect()
		end

		if Target.Value then
			local Target = Target.Value

			local TargetHumanoid = Target:FindFirstChild("Humanoid")

			if TargetHumanoid then
				local TargetHRP = TargetHumanoid.RootPart

				if TargetHumanoid.Health > 0 and TargetHRP then
					local DistanceToEnemy = (TargetHRP.Position - HRP.Position).Magnitude + (TargetHRP.Size.Z / 2) + (HRP.Size.Z / 2)
					local AttackDistance = AttackDistance + (TargetHRP.Size.Z / 2) + (HRP.Size.Z / 2)

					if DistanceToEnemy > AttackDistance then
						local Path = PathfindingService:CreatePath()
						
						Path:ComputeAsync(HRP.Position, TargetHRP.Position + TargetHRP.AssemblyLinearVelocity / 4)

						local Waypoints = Path:GetWaypoints()

						if Waypoints then
							if Waypoints[2] then
								Humanoid:MoveTo(Waypoints[2].Position)
							end
						end
					else
						Humanoid:MoveTo(HRP.Position)
					end
				end
			end
		end
	end)
end

coroutine.wrap(PathfindCompute)()

Anyone know how to fix this?

1 Like

Try setting the NPC to the server-side if that works.

1 Like

Honestly that might’ve fixed it, but I’m not sure since the bug only happens every once in a while.

1 Like

Maybe your client probably sometimes have an issue trying to render the npc, I dunno lol

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.