Skip to Content

NPCs and zombies

Drive an NPC Humanoid with MoveTo, add nearest-player targeting and apply contact damage.

1. Get an NPC

Insert NPC from the Toolbox. It is a model containing a Humanoid and the parts Head, Torso, Larm, Rarm, Lleg and Rleg. Any model with this layout is treated as an NPC.

2. Random wandering

Add a server script to the model:

local npc = script.Parent
local humanoid = npc.Humanoid
local start = npc.Torso.Position

while humanoid.Health > 0 do
	local x = start.X + math.random(-15, 15)
	local z = start.Z + math.random(-15, 15)
	humanoid:MoveTo(Vector3.new(x, start.Y, z))
	humanoid.MoveToFinished:Wait()
	task.wait(1)
end

MoveTo sets the target. MoveToFinished fires when the NPC arrives or the move times out.

3. Nearest-player targeting

World:GetHumanoidsNear returns every living Humanoid in range. Player Humanoids are parented to a Character, so filter on typeof to target players only:

local World = game:GetService("World")
local zombie = script.Parent
local humanoid = zombie.Humanoid
local torso = zombie.Torso

local function nearestPlayer()
	local best, bestDistance = nil, 60
	for _, target in ipairs(World:GetHumanoidsNear(torso.Position, 60)) do
		local body = target.Parent
		if typeof(body) == "Character" then
			local distance = (body.Position - torso.Position).Magnitude
			if distance < bestDistance then
				best, bestDistance = target, distance
			end
		end
	end
	return best, bestDistance
end

while humanoid.Health > 0 do
	local target, distance = nearestPlayer()
	if target then
		humanoid:MoveTo(target.Parent.Position)
		if distance < 4 then
			target:TakeDamage(15)
			task.wait(1)
		end
	end
	task.wait(0.2)
end

4. Cleanup

Destroy the model a few seconds after Died:

humanoid.Died:Wait()
task.wait(5)
zombie:Destroy()

Toolbox zombies

Zombie and Respawning Zombie expose their parameters as value objects on the model:

ValueZombieRespawning Zombie
Health✓✓
Speed✓✓
Damage✓✓
RespawnTime✓

Respawning Zombie respawns on its pad after RespawnTime seconds. NPC Humanoids take damage from tools and explosions like player Humanoids.

On this page