How can I make my AI see target from all sides? (LookVector)

I am making an AI for my horror game and I need it so it can see the player from all sides. Right now the AI can only see the player if the player is in the front of the AI. I have tried finding how to solve this on forums but nothing helped. Also I would be glad if you can possibly make the AI always see you. I would rather the AI to always see you but just seeing the player from all sides is good too

local function canSeeTarget(target)
	if target and target:FindFirstChild("HumanoidRootPart") then
		local origin = TeddyAI.HumanoidRootPart.Position
		local direction = (target.HumanoidRootPart.Position - TeddyAI.HumanoidRootPart.Position).unit * 10000
		local ray = Ray.new(origin, direction)
		local ignoreList = {TeddyAI}

		local hit, pos = workspace:FindPartOnRayWithIgnoreList(ray, ignoreList)

		-- check if it exists
		if hit then
			-- check if it hit
			if hit:IsDescendantOf(target) then
				-- check health
				if target.Humanoid.Health > 0 then
					-- check if target is safe or not
					if not game.Players:GetPlayerFromCharacter(target).Safe.Value then
						-- check if monster can see
						local unit = (target.HumanoidRootPart.Position - getHumPos()).Unit
						local lv = TeddyAI.HumanoidRootPart.CFrame.LookVector
						local dp = unit:Dot(lv)

						if dp > 0 then
							return true
						end		
					end			
				end
			end
		else
			return false
		end	
	end
end

You can create a vision cone using a bit of fun math

local fieldOfView = 60 -- field of view of the AI

local objectSpace = TeddyAI.HumanoidRootPart.CFrame:PointToObjectSpace(targetPos)
local sightAngle = math.deg(math.atan2(objectSpace.Y, -objectSpace.Z))
local inVisionCone = math.abs(sightAngle) <= fieldOfView/2

Just get rid of your DotProduct check. The line if dp > 0 then checks if the character is in front of the AI.

Cant believe thats all I had to do :sweat_smile:

1 Like