NPC Line of sight check causing high ping

In a very small test with about 4 players and 10 AI max at one time, I was getting around 60-400 ping, which is not great.

Script profiler says that the most expensive function in the NPCs functionality is the line of sight check, which runs every update of the behavior tree (Runservice.Stepped)

The line of sight check simply sends out a ray in the direction of the target, and if it hits the target, it returns true. The ray is the expensive part.

I have already done a 1/2 chance to use the previously stored data, but it still seems really expensive for the server.

An idea I had was to only update it every 20 ticks, and use the stored data in the mean time. Not sure how well this would work, but I can’t try until tomorrow.

Any help would be appreciated.

Could you send a snippet of the code you are using to run this check?

Along with this, is it necessary to run it every frame? Adding a bit of delay between scanning can really help reduce server load.

1 Like

I guess the delay is the real answer here.

I’m not on my PC right now, but I can send it over tomorrow .

It’s just one ray cast, checking if the result exists, then asking if it’s the descendant of the target. if so, return true, if not, return false.

Managed to delay it using a simple system.

-- VERY IMPORTANT, THIS "obj" TABLE IS EFFECTIVELY A CLASS. IT'S A FEATURE OF BEHAVIOR TREES (you can probably find it easily on devforum)

local Target = obj.Target
	
	if Target then
		if obj.T >= obj.MaxT then
			obj.T = 0
			
			local Origin = obj.Character.PrimaryPart.Position
			local Distance = (Origin - Target.Head.Position).Magnitude
			local Direction = (Target.Head.Position - Origin).Unit * Distance

			local Ray = workspace:Raycast(Origin, Direction, obj.Params)

			if Ray and Ray.Instance then
				if Target:IsAncestorOf(Ray.Instance) then
					obj.Class:PlaySound("Spotted")

					obj.Bools.LineOfSight = true

					return SUCCESS
				end
			end
		else
			obj.T += 1
			
			if obj.Bools.LineOfSight then
				return SUCCESS
			else
				return FAIL
			end
		end
	end
	
	obj.Bools.LineOfSight = false
	
	return FAIL

This has genuinely boosted performance by a ton.

Thanks for your advice.

1 Like

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