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