How do i fix this weird lag on npc whenever it is close to player it starts to lag

,

robloxapp-20240629-1122331.wmv (1.5 MB)

heres the script

local PathfindingService = game:GetService("PathfindingService")

local npc = script.Parent

local humanoid = npc:WaitForChild("Humanoid")
local hrp = npc:WaitForChild("HumanoidRootPart")
humanoid.WalkSpeed = 100
hrp:SetNetworkOwner(nil)

local walkAnim = humanoid.Animator:LoadAnimation(script.Walk)
local attackAnim = humanoid.Animator:LoadAnimation(script.Attack)

local pathParams = {
	AgentHeight = 5,
	AgentRadius = 3,
	AgentCanJump = false,
}

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.FilterDescendantsInstances = {npc}

local lastPos
local animPlaying = false

local RANGE = 150
local DAMAGE = 40


local function canSeeTarget(target)
	local orgin = hrp.Position
	local direction = (target.HumanoidRootPart.Position - hrp.Position).Unit * RANGE
	local ray = workspace:Raycast(orgin, direction, rayParams)

	if ray and ray.Instance then
		if ray.Instance:IsDescendantOf(target) then
			return true
		else
			return false
		end
	else
		return false
	end
end

local function findTarget()
	local players = game.Players:GetPlayers()
	local maxDistance = RANGE
	local nearestTarget

	for i, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude

			if distance < maxDistance and canSeeTarget(target) then
				nearestTarget = target
				print("TAR")
				maxDistance = distance
			end
		end
	end

	return nearestTarget
end

local function getPath(destination)
	local path = PathfindingService:CreatePath(pathParams)

	path:ComputeAsync(hrp.Position, destination.Position)

	return path	
end

local function attack(target)
	local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude
	local debounce = false

	if distance > 5 then
		humanoid:MoveTo(target.HumanoidRootPart.Position)
	else
		if debounce == false then
			debounce = true

			npc.Head.AttackSound:Play()
			attackAnim:Play()
			target.Humanoid.Health -= DAMAGE
			task.wait(0.5)
			debounce = false
		end
	end
end

local function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then
		for i, waypoint in pairs(path:GetWaypoints()) do
			path.Blocked:Connect(function()
				path:Destroy()
			end)

			if animPlaying == false then
				walkAnim:Play()
				animPlaying = true
			end

			attackAnim:Stop()

			local target = findTarget()

			if target and target.Humanoid.Health > 0 then
				lastPos = target.HumanoidRootPart.Position
				attack(target)
				break
			else
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
				end

				if lastPos then
					humanoid:MoveTo(lastPos)
					humanoid.MoveToFinished:Wait()
					lastPos = nil
					break
				else
					humanoid:MoveTo(waypoint.Position)
					humanoid.MoveToFinished:Wait()
				end
			end
		end
	else
		return
	end
end

local function patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local randomNum = math.random(1, #waypoints)
	walkTo(waypoints[randomNum])
end

while task.wait(0.2) do
	patrol()
end
5 Likes

Get rid of the print statement, print statements are great for debugging but they can cause huge lag. It should work just fine then.

If this works, mark it as the solution.

1 Like

i removed the print statement but it did not work

If its still lagging then i’m pretty much not sure. Also why are you using rays? This code seems kinda outdated, are you using an old tutorial?

yes the script is an 2 year old tutorial

I think you should try making the code yourself then because there’s too much going on there, it would be way too hard.

alright thanks i’ll use annother script

Try use one that is recent, but why don’t you make it yourself? Is it hard for you?

try this
humanoidrootpart:SetNetworkOwner(nil)

oh yea btw there might be typo on the command above cuz im on mobile lol

why this works??
The reason why the npc is lagging is because when the npc is far away from the player , the server is taking care of its physics . However , when it is closer to a player, roblox would off load the stress of calculating the physics on the server to the client. This cause the npc to be like glitchy as it is hopping from server owner to client owner . Hope this helps

Yeah you need a player instance, not nil. I didn’t realise he was talking about the NPC’s movement being glitchy. I thought he meant on the player’s client that there was an FPS drop or something.

Hi! Netwrokowner can be set to nil . Imagine this . If the part is own by nobody, it would be automatically be own by the server . Setting networkowner basically set the owner of the part to the client stated or the server and prevent the owner from chaning

more info:

Oh yeah I know that, but that wouldn’t change anything. Because it was already owned by the server to begin with right? Or is it because when the player is close the client automatically owns it, yep probably.

Yes . The changing of network owner is the cause of the lag observed