Why does my zombie that requires line of sight only work in one direction?

Hello. I am trying to make a simple zombie script where the zombie follows the nearest player. However, this player needs to be in the line of sight of the zombie. Below is the entire zombie script:

local character = script.Parent
local humanoid = character.Humanoid

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {character}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

local function findNearestTorso()
	local nearestTorso = nil
	for i, v in pairs(game.Players:GetPlayers()) do
		if v.Character ~= nil then
			local t = v.Character:FindFirstChild("HumanoidRootPart")
			if t and (t.Position - character.HumanoidRootPart.Position).Magnitude <= 100 then
				local rayOrigin = character.HumanoidRootPart.Position
				local rayDirection = t.Position
				local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
				if raycastResult then
					local inst = raycastResult.Instance
					print(inst.Name)
					if inst:FindFirstAncestor(t.Parent.Name) then
						if nearestTorso then
							if (nearestTorso.Position - character.HumanoidRootPart.Position).Magnitude > (h.Position - character.HumanoidRootPart.Position).Magnitude then
								nearestTorso = t
							end
						else
							nearestTorso = t
						end
					end
				else
					print("noray")
				end
			end
		end
	end
	
	return nearestTorso
	
end

while wait(.1) do
	local t = findNearestTorso()
	if t then
		humanoid:MoveTo(t.Position)
	else
		humanoid:MoveTo(character.HumanoidRootPart.Position)
	end
end

I know that it is able to find the nearest torso correctly without the raycasting. I have also visualized the rayOrigin and rayDirection and both are in the correct positions. Despite this, the zombie only follows me if I am standing in a certain exact direction from it. I really can’t seem to find the root of this issue.

1 Like

This needs to be a direction, not a position. Change to:

local rayDirection = t.Position - rayOrigin
2 Likes