How can I make a npc detect if there is always a wall?

I took this out of another topic but as long as the npc detects or not a wall it always stays with the same value, what do I do?

local npc = script.Parent
local head = npc.Head
local Lenght = 15
local Shoot = false
local Ray = Ray.new(head.Position, head.CFrame.LookVector*Lenght)
local Wall, HitPosition, Normal, Material = workspace:FindPartOnRay(Ray, npc)

while wait() do
	if Wall then 
		Print("yes")
	else
		Print("no")
	end
end

example: if the npc comes out facing a wall, the print will always come out that if even so without detecting the wall and vice versa

Do the raycasting inside the loop.

local npc = script.Parent
local head = npc.Head
local Lenght = 15
local Shoot = false

while wait() do
	local Ray = Ray.new(head.Position, head.CFrame.LookVector*Lenght)
	local Wall, HitPosition, Normal, Material = workspace:FindPartOnRay(Ray, npc)
	if Wall then 
		Print("yes")
	else
		Print("no")
	end
end
3 Likes
  1. I’d recommend using the new raycasting methods, as ray.new() has been deprecated
  2. I don’t really like the idea of raycasting in a while wait() loop, this seems like it could pretty performance intensive. Why not instead raycast everytime the npc moves instead, as the NPC would be in the same position relative to the wall if they weren’t moving
local npc = script.Parent
local head = npc.Head
local Lenght = 15
local Shoot = false
local RunService  = game:GetService("RunService")

RunService.RenderStepped:Connect(function()
    if npc.Humanoid.MoveDirection.Magnitude > 0 then  -- if npc is moving
        -- Set an origin and direction of ray
	    local rayOrigin = head.Position
	    local rayDirection = head.CFrame.LookVector*Lenght
            
        local raycastParams = RaycastParams.new()
	    raycastParams.FilterDescendantsInstances = {npc:GetChildren()}  -- Parts you want ray to ignore
	    raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

	    local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams) 
        if raycastResult then   -- If the ray hit anything
            print("yes")
        else
            print("no")
        end
    end
end)
1 Like