How to let client handle npc loads

I have a server script that basically makes the npc always face the player by using align orientation and updating the orientation using heartbeat event. the problem is that this is extremely taxing on the server and gets really laggy when I spawn more than 5 npcs.

I have tried doing this on the client side but the npc is stuck at one orientation even if I dont set the networkowner to nil. basically I just had a client runservice that did a loop through an npc folder and set the orientation to the player

I have heard about using remote events to let the client handle the work but I’m unsure on how to approach it. And what should the networkowner be?

function BaseNPC:Orientation()
	local AlignOrientation = self._Model.HumanoidRootPart.RootAttachment:FindFirstChild("AlignOrientation")
	local player = PS:FindFirstChild(self._Model:GetAttribute("Target"))
	if not player or not player.Character then return end
	if not AlignOrientation then
		 AlignOrientation = self:AlignOrientationSetUp()
	else
		local PlayerPosition = player.Character.HumanoidRootPart.Position
		local NPCPosition = self._Model.HumanoidRootPart.Position
		local Difference = (NPCPosition - PlayerPosition)
		local Angle = math.atan2(Difference.X, Difference.Z)
		
		if not self._Model:GetAttribute("Stunned") then 
			AlignOrientation.CFrame = CFrame.Angles(0, Angle, 0)
		else
			AlignOrientation.CFrame = CFrame.Angles(0,0,0)
		end
	end
end

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

I assume you make sure to set the Attachment0 of the AlignPosition in your setup function;

can try this, havent tested, seems easier to use the LookAtPosition than calculate angles

function BaseNPC:Orientation()
	local AlignOrientation = self._Model.HumanoidRootPart.RootAttachment:FindFirstChild("AlignOrientation")
	local player = PS:FindFirstChild(self._Model:GetAttribute("Target"))
	if not player or not player.Character then return end
	if not AlignOrientation then
		 AlignOrientation = self:AlignOrientationSetUp()
	else
		local PlayerPosition = player.Character.HumanoidRootPart.Position
		AlignOrientation.AlignType = Enum.AlignType.PrimaryAxisLookAt
		AlignOrientation.Mode = Enum.OrientationnAlignmentMode.One
		AlignOrientation.LookAtPosition = player.Character.HumanoidRootPart.Position
		
		if not self._Model:GetAttribute("Stunned") then 
			AlignOrientation.LookAtPosition = playerPosition
		else
			AlignOrientation.LookAtPosition = Vector3.zero
		end
	end
end

Note: this script will follow the Y axis as well, you can adjust that but I didnt want to write all that out

1 Like

Thanks I’ll be trying this tomorrow but I also want to know if this can be done on the client securely or would it be better to let the server handle this.