#How would I make this script also target NPCs

1 messages · Page 1 of 1 (latest)

pine pewter
#

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

#

for index, solidersA in npcModels do
local humanoid = solidersA:FindFirstChildOfClass("Humanoid")

if not solidersA:IsA("Model") then
    continue
end

if not humanoid then
    continue
end

local function checking()
    while task.wait(1) do
        if checkSight(solidersA) then

        else
            
        end
    end
end

coroutine.wrap(checking)()

end