So i am trying to code npc which will detect if player is in front of him. i send rays every 1 degree. npc’s FOV is 120 degrees, thats why i iterate between -60 and 60. but it doesnt work can anyone help me?
local runtime = game:GetService("RunService")
local npc1 = game.Workspace:WaitForChild("Ray")
local character = game:GetService("Players").LocalPlayer.Character
while wait(5) do
local origin = npc1.Head.Position
local direction = npc1.Head.CFrame.LookVector * 100
local raycastResults = {}
for i = -60, 60 do
local raycastResult = workspace:Raycast(origin, (CFrame.new(direction) * CFrame.Angles(0, math.rad(i), 0)).Position)
if raycastResult then
table.insert(raycastResults, raycastResult)
end
end
npc1.Head.BrickColor = BrickColor.Yellow()
for i, ray in pairs(raycastResults) do
print(ray.Instance)
if ray.Instance.Parent:FindFirstChild("Humanoid") then
local char = ray.Instance.Parent
local player = game.Players:GetPlayerFromCharacter(char)
if player then
print("YEY")
end
end
end
end