NPC that attacks player when near seems to attack a delayed replication of the player (on the server-side)

1.I’m trying to make a npc attack the player when in proximity. I don’t want it to take much of a toll on performance, as there will be many of these npcs. Also the npc is using a hitbox part

  1. It appears as if my movement is slower server-side than on the client-side, so the npc deals damage to me even when I’m not close to it, what I found is that in the server the distance is accurate but what I see as the client does not match that.

– here is what I see (the client) vs what is going on in the server

  1. I have tried alternating the network ownership of the npc between the client and the server but it just looks like the npc is teleporting when the change occurs.
-- the attack section

local hitbox = Figure:WaitForChild("hitbox")
local isAttacking = false

hitbox.Touched:Connect(function(hitPart)
	-- Check if the NPC is not already attacking and if the part hit belongs to a character (not tagged "darksoul")
	if not isAttacking and hitPart.Parent:IsA("Model") and not hitPart.Parent:HasTag("darksoul") then
		local humanoid = hitPart.Parent:FindFirstChildOfClass("Humanoid")
		if humanoid then
			isAttacking = true
			script.Parent.CanAttack.Value = true
			humanoid.Health -= 10
			task.wait(debounceDelay)
			script.Parent.CanAttack.Value = false
			isAttacking = false
		end
	end
end)


Here is the code for setting the network ownership of the npc to the server:

local monster = script.Parent
local primaryPart = monster.PrimaryPart

-- Ensure the monster has a PrimaryPart set
if primaryPart then
	primaryPart:SetNetworkOwner(nil)
else
	warn("Monster's PrimaryPart is not set. Ensure it's properly assigned.")
end

Any help will be appreciated! I just need to get the npc to attack the player when in proximity, if you can give any simple solutions that are not too performance-heavy, I will try them out too

1 Like

This behavior is normal, the server receives delayed requests from the client regarding their movements (physics changes) because of latency.

One option is to estimate where the player might actually be on their client when starting to check if a player is close enough in the NPC’s code. For example:

local DAMPENING = 5

local targetCFrame = NPC_TARGET.CFrame
local adjustedVelocity =  targetCFrame:VectorToObjectSpace(NPC_TARGET.AssemblyLinearVelocity) / DAMPENING

targetCFrame *= adjustedVelocity

And you would use targetCFrame in place of whatever you had as your target’s server position. Adjust dampening constant as necessary since it might predict too forward or not enough, etc.

Thank you so much!

at first I tried it out and it wasn’t working but I changed a few things in the game and now it’s working just fine!

Thank you

1 Like

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