AI can able to detect player even though player is not touching Raycast

Hello, can someone help me with this? the AI can detect the player even though player is not touching the raycast… here’s the code

I’m kinda bad at scripting so please don’t judge

local npc = script.Parent

local raycastParams =
raycastParams.FilterDescendantsInstances = {npc.Head}

local pathfindingService = game:GetService("PathfindingService")
local humanoid = npc.Humanoid
local lastSeenTime = 0
local detectionDistance = 50

while true do
	for _, player in ipairs(game.Players:GetPlayers()) do
		if player.Character then
			local origin = npc.Head.Position
			local direction = npc.Head.CFrame.LookVector * detectionDistance
			local playerModel = player.Character
			local playerParts = {}
			for _, part in ipairs(playerModel:GetDescendants()) do
				if part:IsA("BasePart") then
					table.insert(playerParts, part)
			-- add the player model to the ignore list
			table.insert(playerParts, playerModel)
			local result = workspace:FindPartOnRayWithIgnoreList(, direction), playerParts)

			if result and (result.Position - npc.Head.Position).Magnitude <= detectionDistance then
				lastSeenTime = tick()

				local path = pathfindingService:CreatePath()
				path:ComputeAsync(npc.Head.Position, playerModel.HumanoidRootPart.Position)

				if path.Status == Enum.PathStatus.Success then
					local waypoints = path:GetWaypoints()
					for _, waypoint in ipairs(waypoints) do

	if tick() - lastSeenTime > 2 then


The FindPartOnRayWithIgnoreList expects two arguments, the second being a list of parts to ignore. It seems like you were trying to use that list as a white list but it works like a black list.
The ray is not hitting the player’s character, it is most likely hitting any other random part since you don’t check whether that part belongs to the player or not.

By the way, FindPartOnRayWithIgnoreList is deprecated. You should use :Raycast() instead. This method takes a third argument which is a RaycastParams through which you can specify a list of instances to filter (black list or white list).

1 Like

Oh, how do I implement it on the code?