Raycast to see if object is visible does not work if wall is behind object

I am trying to execute a remote event from a local script when the player sees an AI, using a box attached to the AI character to detect rays:

image

The script works if the AI is stood out in the open with no walls, however if there is a wall behind it, the raycast does not return “seen”

Here is the script:

local partToCheck = workspace:GetDescendants()

local camera = workspace.CurrentCamera
local replicated = game:GetService("ReplicatedStorage")
local event = replicated:WaitForChild("Seen")

local function seen(player)
	for i, v in pairs(workspace:GetDescendants()) do
		if v.Name == "hitbox" then
			local partToCheck = v 
			
local vector, inViewport = camera:WorldToViewportPoint(partToCheck.Position)
local onScreen = inViewport and vector.Z > 0

-- Raycast outward:
local ray = camera:ViewportPointToRay(vector.X, vector.Y, 0)
local raycastParams = RaycastParams.new()
			raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
			raycastParams.FilterDescendantsInstances = {partToCheck, game.Players.LocalPlayer.Character}
local raycastResult = workspace:Raycast(ray.Origin, ray.Direction * 10000, raycastParams)

-- Final check:
local isVisible = onScreen and not raycastResult
if isVisible then
				event:FireServer()
				print("seen")
	end
		end
	end
end

while wait(0.2) do 
	local seen = seen()
	if seen then 
		seen()
	end
end

one interesting thing i noticed that the partToCheck variable which is in the FilterDescendantsInstances property. On line one you define partToCheck as alll descendants of the workspace. Meaning you are filtering out everything in the workspace when you raycast. You make a new variable with the same name later on which is bad practice. A possible issue is that you are filtering the part you want to detect. Try taking partToCheck out of the filter list.

If that doesnt work try using the plyr camera’s position and for the direction use (partToCheck.Position - camera.Position).Unit * 10000

Where would I use this within the script

replace that with ray.direction *10000 where you use the raycast function

Sadly still doesn’t detect the brick if it is in front of a wall

does the brick have canQuerry enabled?

and also check if you still have it in RayInfo.FilterDescendantInstances. If you do, take it out