BLOXBUILDS
Discord
Back
COMBAT

Simple Enemy NPC

Paste as a Script inside an NPC model that has a Humanoid and a HumanoidRootPart. The NPC walks to the nearest player and attacks when it gets close.

-- Paste as a Script inside an NPC model.
-- The model needs a Humanoid and a HumanoidRootPart.

local Players = game:GetService("Players")

local DAMAGE = 10
local ATTACK_RANGE = 5
local CHASE_RANGE = 80
local ATTACK_COOLDOWN = 1

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid") :: Humanoid
local root = npc:WaitForChild("HumanoidRootPart") :: BasePart
humanoid.WalkSpeed = 14

local lastAttack = 0

while npc.Parent and humanoid.Health > 0 do
	local closestRoot: BasePart? = nil
	local closestHumanoid: Humanoid? = nil
	local closestDistance = CHASE_RANGE

	for _, player in ipairs(Players:GetPlayers()) do
		local character = player.Character
		local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
		local targetHumanoid = character and character:FindFirstChildOfClass("Humanoid")
		if targetRoot and targetRoot:IsA("BasePart") and targetHumanoid and targetHumanoid.Health > 0 then
			local distance = (targetRoot.Position - root.Position).Magnitude
			if distance < closestDistance then
				closestRoot = targetRoot
				closestHumanoid = targetHumanoid
				closestDistance = distance
			end
		end
	end

	if closestRoot and closestHumanoid then
		humanoid:MoveTo(closestRoot.Position)
		if closestDistance <= ATTACK_RANGE and os.clock() - lastAttack >= ATTACK_COOLDOWN then
			lastAttack = os.clock()
			closestHumanoid:TakeDamage(DAMAGE)
		end
	end

	task.wait(0.25)
end