NPC AI Controller script help

This is a working controller script for AI in my game. It works ok but it has two problems. One problem is I need to slow down how often it checks to see if players are in range to attack.

The second problem is if the monster kills the player it stands there and swings its weapon at the location of the dead player until it is killed. I need it to return to home spawn if the player is killed.

Anyone able to tackle these issues?

local hum = script.Parent:WaitForChild("Humanoid")
local root = script.Parent:WaitForChild("HumanoidRootPart")
local spawnPos = script.Parent:WaitForChild("SpawnPosition")

local visionRange = 60
local attackRange = 3
local abandonRange = 50
local abandonRangeFromHome = 200

local target = nil

while wait() do
	local targetIsInWorkspace
	pcall(function()
		targetIsInWorkspace = target.Parent == game.Workspace
	end)

	if targetIsInWorkspace then
		--calculate distance and attack player
		local plrRoot = target.HumanoidRootPart
		local distance = (root.Position - plrRoot.Position).magnitude
		local distancefromhome = (spawnPos.Value - plrRoot.Position).magnitude

		hum:MoveTo(plrRoot.Position - CFrame.new(root.Position, plrRoot.Position).LookVector * attackRange)

		if distance <= attackRange +2 then
			script.AttackRemote:Fire(plrRoot)
		end

		if distance > abandonRange then
			print("Abandoning Target")
			target = nil
			hum:MoveTo(spawnPos.Value)
		end

		if distancefromhome > abandonRangeFromHome then
			print("Abandoning Target")
			target = nil
			hum:MoveTo(spawnPos.Value)
		end

	else
		--see if any players are in range
		for i,v in pairs(game.Players:GetChildren()) do

			if not game.Workspace:FindFirstChild(v.Name) then continue end
			local char = game.Workspace[v.Name]
			local plrRoot = char.HumanoidRootPart

			local distance = (root.Position - plrRoot.Position).magnitude
			local distancefromhome = (spawnPos.Value - plrRoot.Position).magnitude

			if distance < visionRange and distancefromhome < abandonRangeFromHome then
				print("Targeting "..v.Name)
				target = char
			end

		end

	end

end

Thanks.

wait() equals approx. every .03 seonds…

cHANGE To:

wait(1) would be; recalc every 1 second…

OR To slow down just the damage…

if distance <= attackRange +2 then
                    wait(?) -- backswing
		script.AttackRemote:Fire(plrRoot)
                    wait(?) -- cool-down
	end
1 Like

And, I will guess that some other script, stops the NPC , and does the attack animtion…?

Correct there is a second script that handles the attacks.

Um… so maybe some other script anchors the NPC or turns his speed to zero, or disables the above script…

Why does the NPC not stop his attack animation?
Does the above, keep looping? Put a print() in it…
Start de-bugging…
Start checking all of your assumptions… One, or more are wrong.