Enemy's interrupt each others raycasts

Hello! I was working on an enemy npc system and it involves raycasting to see if the player is in view, which works great and all as long as it’s only one enemy. Upon adding multiple enemies, the raycast gets interrupting and thinks that the player is no longer in view (which they still are).

Here’s the code:

-- Function to see if the enemy can see the target
local function canSeeTarget(target)
	local origin = Enemy.HumanoidRootPart.Position
	local direction = (target.HumanoidRootPart.Position - origin).unit * 40
	local ray = Ray.new(origin, direction)

	local hit = workspace:FindPartOnRay(ray, Enemy) -- No need for ignore lists!

	if hit and hit:IsDescendantOf(target) then
		return true
	end

	return false
end

local function findTarget()
	local players = game.Players:GetPlayers()
	local maxDistance = 30 -- 10,000
	local nearestTarget

	for index, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (script.Parent.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude

			if distance < maxDistance and canSeeTarget(target) then
				nearestTarget = target
				maxDistance = distance
			end
		end
	end

	return nearestTarget
end

Check out the Filter options of the Raycasting documentation.

There’s also this tutorial: Hit detection with lasers | Documentation - Roblox Creator Hub

1 Like

Replace this function with your current one and let me know if it works!

-- Function to see if the enemy can see the target
local EnemiesFolder=workspace.Enemies -- If you have a folder for enemies, change the path here.
local Parameters=RaycastParams.new()
Parameters.FilterType=Enum.RaycastFilterType.Exclude
Parameters.FilterDescendantsInstances={EnemiesFolder}

local function canSeeTarget(target)
	local origin = Enemy.HumanoidRootPart.Position
	local direction = (target.HumanoidRootPart.Position - origin).unit * 40

	local hit = workspace:Raycast(origin, direction, Parameters)

	if hit and hit:IsDescendantOf(target) then
		return true
	end

	return false
end
2 Likes

I actually did it a different way, I used collision groups to let the enemies see through each other. Thanks anyways! :slight_smile:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.