Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do you make a zombie script which detects you from a distance?

I need to make a zombie which can detect players from a distance

2 answers

Here is a good script that detects the nearest player and has the zombie follow towards. It calls a function to scan all existing players, finds their distance from the zombie, then selects the closest distance for the zombie to follow. Simply put this in the zombie's avatar.

wait(1) --Loading

function findNearestTorso(pos) --Function that finds the nearest player in range to the zombie
	local list = workspace:GetChildren()
	local torso = nil
	local dist = 1000 --Change range (in studs) here.
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do --For every child in the workspace do
		temp2 = list[x]
		if temp2:IsA("Model") and temp2.Name ~= script.Parent.Name then --The child is a model and isn't a zombie.
			temp = temp2:findFirstChild("HumanoidRootPart") --Find the player's torso.
			human = temp2:findFirstChild("Humanoid") --Find the player's humanoid.
			if temp and human and human.Health > 0 then --The player is still alive.
				if (temp.Position - pos).magnitude < dist then --The distance between the player and the zombie is the closest so far.
					torso = temp
					dist = (temp.Position - pos).magnitude --Find the distance between the player and zombie.
				end
			end
		end
	end
	return torso
end

while wait() do
	local target = findNearestTorso(script.Parent.Torso.Position)--Calls the function
	if target ~= nil then --If the character's torso still exists then
		script.Parent.Humanoid:MoveTo(target.Position, target) --Move the zombie to the player
	end
end

Hey there! Just letting you know that SH is not a request site, please put at least some effort for what you're attempting to do :-) https://scriptinghelpers.org/help/community-guidelines

Also, I would recommend looking into magnitude. This is a way to be able to determine the distance between two objects by subtracting one from the other to get a third point; which therefore can be inputted into the Pythagorean theorem to provide you with a distance between the two objects. From there, you can do something like this:

local magnitude = (part1.Position - part2.Position).magnitude
if magnitude < 10 then
	--make the zombie move to the player
end

Here's the wiki page for further details. http://wiki.roblox.com/index.php?title=Magnitude

This discussion is preserved as it was. New answers, comments, and votes are closed.