I am following this tutorial and I tried to make it also detect enemy NPCs but it doesn't work
https://devforum.roblox.com/t/how-to-create-a-realistic-npc-eyesight-system/2456522
My attempt:
local CollectionService = game:GetService("CollectionService")
local solidersA = CollectionService:GetTagged("SoldiersA")
local viewRange = 650
local fieldOfView = 60
local enemyLastDetected = nil
local function raycast(solidersA, start, finish)
local parameters = RaycastParams.new()
parameters.FilterDescendantsInstances = {solidersA}
parameters.FilterType = Enum.RaycastFilterType.Exclude
local raycast = workspace:Raycast(start, (finish - start), parameters)
if raycast then
return true
else
return false
end
end
local function checkSight(npc)
local detectable = {}
local taggedEnemies = CollectionService:GetTagged("SoldiersB")
for index, enemy in taggedEnemies do
table.insert(detectable, enemy)
end
for index, enemy in detectable do
if enemy:IsA("Humanoid") then
enemy = enemy.Torso
end
local headPosition = npc.Head.Position
local enemyPosition = enemy.Position
local headCFrame = npc.Head.CFrame
local direction = (enemyPosition - headPosition).Unit
local lookVector = headCFrame.LookVector
local dotProduct = direction:Dot(lookVector)
local angle = math.deg(math.acos(dotProduct))
local distance = (headPosition - enemyPosition).Magnitude
if angle > fieldOfView then
continue
end
if distance > viewRange then
continue
end
if raycast(npc, headPosition, enemyPosition) then
return
end
if enemy:IsA("Model") then
enemyLastDetected = enemy.Parent
else
enemyLastDetected = enemy
end
return true
end
end
Introduction Hello everyone! In this tutorial, I’m going to teach you how to create a realistic NPC eyesight system so that NPCs can see and detect players and other objects. For example, you could use this to make a guard detect a player. Steps Create a script in ServerScriptService and name it whatever you’d like. This script will cont...