I must improve enemy ai

hello, I want to make a good enemy ai but I must improve it (there will be area for him, if you leave his area he will stop following you) how can I make this?(npc is R15 btw)

image

I don’t know coding too much here’s the code:

local hrpOfNPC = npc:WaitForChild("HumanoidRootPart")

local plrsHit = {}

local maxDistance = math.huge


npc.Humanoid.Touched:Connect(function(touch)

	if game.Players:GetPlayerFromCharacter(touch.Parent) and not plrsHit[game.Players:GetPlayerFromCharacter(touch.Parent)] then

		plrsHit[game.Players:GetPlayerFromCharacter(touch.Parent)] = true
		
		touch.Parent.Humanoid:TakeDamage(20)
		
		wait(1)

		plrsHit[game.Players:GetPlayerFromCharacter(touch.Parent)] = false	
	end
end)


while wait() do
	
	local plrs = game.Players:GetPlayers()
	
	local closestHRP
	
	for i, plr in pairs(plrs) do
		
		if plr.Character and plr.Character:FindFirstChild("HumanoidRootPart") and plr.Character.Humanoid.Health > 0 then
			
			local hrp = plr.Character.HumanoidRootPart
			
			local distanceBetween = (hrpOfNPC.Position - hrp.Position).Magnitude
			
			
			if not closestHRP then closestHRP = hrp end
			
			if (hrpOfNPC.Position - closestHRP.Position).Magnitude > distanceBetween then
				
				closestHRP = hrp
				
			end
		end
	end
	
	if closestHRP and (hrpOfNPC.Position - closestHRP.Position).Magnitude <= maxDistance then npc.Humanoid:MoveTo(closestHRP.Position) end
end
2 Likes

I think that your solution is Region3 because you can create an invisible area with that and then detect if any players are in that invisible area and if they are then simply make the enemy ai chase them until they die because the enemy ai killed them or until they get out of the invisible area.

2 Likes

thanks, I’ll try it when I learned that

I recommend using Zone+ by hd admin its really ez to use you wont believe it

zone.playerEntered:Connect(function(player)
    print(("%s entered the zone!"):format(player.Name))
--noob follow enemy
end)

zone.playerExited:Connect(function(player)
    print(("%s exited the zone!"):format(player.Name))
--noob go base (check if players in zone is 0 before doing this though)
end)
1 Like

It looks good but how can I find that “zone”?

You can find it here