How can I make an enemy follow you either when you take damage or when you get close?

local npc = script.Parent
local debounce = false
local wasAttacked = false
local wasDistance = false

npc.Humanoid.Touched:Connect(function(hit)
	if hit and game.Players:GetPlayerFromCharacter(hit.Parent) then
		if debounce == false then
			debounce = true
			hit.Parent.Humanoid:TakeDamage(10) -- U SHOULD TO CHANGE THIS!!!
			wait(.25) -- AND THIS!!!
			debounce = false
		end
	end
end)


function FindPlayer(Position)
	local list = game.Workspace:GetChildren()
	local torso = nil
	local distance = 50 -- CHANGE THIS TOO!!!
	local HRP = nil
	local humanoid = nil
	local player = nil
	
	for i = 1, #list do
		player = list[i]
		if (player.ClassName == "Model") and (player ~= script.Parent) then
			HRP = player:FindFirstChild("HumanoidRootPart")
			humanoid = player:FindFirstChild("Humanoid")
			
			if (HRP ~= nil) and (humanoid ~= nil) and (humanoid.Health > 0) then
				if (HRP.Position - Position).Magnitude < distance then
					torso = HRP
					distance = (HRP.Position - Position).Magnitude
					
					if distance <= 40 then
						wasDistance = true
					else
						wasDistance = false
					end
				end
			end
		end
	end
	
	return torso
end



npc.Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
	wasAttacked = true
	while wasAttacked == true or wasDistance == true do
		wait(1)
		local target = FindPlayer(script.Parent.HumanoidRootPart.Position)

		if target ~= nil then
			script.Parent.Humanoid:MoveTo(target.Position, target)
		end
	end
	
end)


--while true do
--	wait(1)
--	local target = FindPlayer(script.Parent.HumanoidRootPart.Position)
	
--	if target ~= nil then
--		script.Parent.Humanoid:MoveTo(target.Position, target)
--	end
--end

So this is my script at the enemy. at the moment when I hit him he follows me, and when the distance is large does not stop going, but the problem is that I do not know how to do the following:

  1. If I do not hit him for more than 10 seconds, for example, he returns to his spawnpoint
  2. If I am away from him a lot, he also returns to his spawnpoint
  3. If I hit him, he starts to follow me.

Can you tell me how it can be done?

Use os.clock() in a variable and update it everytime the NPC takes damage, you can use Humanoid.HealthChanged to detect damage. Then every like 0.5-1 second check if the health is the same as it was 10 seconds ago (thanks to the os.clock() variable).

Every frame check the magnitude between the NPC and the target, if it’s higher than X studs tell the NPC to go back to the starting point (perhaps 100 or 200 studs will do depending on what type of NPC it is).

This depends on your weapon system or the way you deal damage to it, which I don’t know how you handle so it’s hard to give an answer but my suggestion is to use a BindableEvent and to fire it everytime you decide to damage it, then update the NPC’s target to your character

1 Like