Raycasting isn't working correctly

Hey! I’m working on a stealth game filled with NPCs and I want the NPCs to be able to notice corpses when one is visible. I am trying to use Raycasting as a way to make them be able to notice corpses without any instances in front of them. I am also making it so they can detect the corpse from a magnitude from less than or equal to 35. The only problem I have is that, whenever I run the game, the NPCs notice the corpses through walls, and sometimes when I put the corpse next to them, they don’t have any reaction. Can someone please help me with my problem?

local foundCorpse = false

function corpseDiscovered(corpse)
    -- Stuff
end

while wait() do
	if foundCorpse == false then
    	for i, v in pairs(game.Workspace:GetDescendants()) do
    		if v:IsA("BoolValue") and v.Name == "Dead" then
    			if v.Value == true then
    				if (v.Parent.HumanoidRootPart.Position - 
script.Parent.HumanoidRootPart.Position).magnitude <= 40 then
					local ray = Ray.new(v.Parent.HumanoidRootPart.CFrame.Position, 
script.Parent.HumanoidRootPart.CFrame.Position)
					
					local hit = game.Workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent, 
v.Parent})
					if hit then

				    	else
							foundCorpse = true
						    corpseDiscovered(v.Parent)
					    	break
				    	end
			    	end
		    	end
	    	end
    	end
	end
end

Someone please help me with this, I’ve been trying to fix this for the past 1 and a half hours now lol ( Sorry if the script is messed up, idk how to fix it :confused: )

1 Like

The second parameter for the ray is the direction of the ray, not the end point of the ray. so instead of:

local ray = Ray.new(v.Parent.HumanoidRootPart.CFrame.Position, script.Parent.HumanoidRootPart.CFrame.Position)

Do:

local ray = Ray.new(v.Parent.HumanoidRootPart.Position, CFrame.new(script.Parent.HumanoidRootPart.Position - v.Parent.HumanoidRootPart.Position).LookVector.Unit * 100)

And no need to do CFrame.Position, not only is it slower, but it also is longer and more messy; just use Position instead.

1 Like

Ok! I’ll try that out! Thanks (30 charrrs)

It didn’t work, the NPC was still able to see the corpse through the wall :confused:

Nevermind, I was able to find a solution for my problem. I just used the lookvector of the NPC and made it so that if it sees a corpse then it will react properly.