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

2 Likes

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.

2 Likes

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

2 Likes

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.

4 Likes

@Ethanthegrand14

--Insert this in your script
local HRP = AI.HumanoidRootPart
local Lenght = 15
local Shoot = false
local Ray = Ray.new(HRP.Position, 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
end
6 Likes

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

1 Like