How do you check if there is a wall/object infront of an NPC?

So i have an AI with a gun that attacks any players or NPCs that gets close enough to it. But my issue is that when a player or NPC is behind a wall the AI will still try and shoot you, even though you are behind an object, How would i solve this? Help would be much appreciated. Thanks


i think you can raycast from the npc towards the target (or all nearby) player, anything that intersects and is cancollide = true then don’t shoot.


I know nothing about raycasting, an example or some more information would be helpful :+1:


Here are code examples, you don’t need to read the whole thing as it covers also creating some sort of beam but you will learn how to cast rays and find parts that collide with them.



--Insert this in your script
local HRP = AI.HumanoidRootPart
local Lenght = 15
local Shoot = false
local Ray =, HRP.CFrame.LookVector*Lenght)--it create a raycast From your AI.HumanoidRootPart to 15 
local Wall, HitPosition, Normal, Material = workspace:FindPartOnRay(Ray, AI)
if Wall then --If the Wall exist then …
    Shoot = false --Dont Shoot
else --if dont exist a Wall between the AI and the Target then …
    Shoot = true

Wow, it works. Thanks, the AI should be less dumb now.

1 Like