You can use Vector3:Dot() to tell whether the position of PartB is within the FOV of PartA's LookVector. Basically, it returns a negative when it is behind the part and returns to a positive when it is in front of it.
There's a YouTube tutorial and a DevForum post about it and it might be simpler than my explanation.
local NPC = workspace.NPC
local sightLimit = 0.7071
game:GetService("Players").PlayerAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function(Character)
local Head = Character:WaitForChild("Head")
local Humanoid = Character:WaitForChild("Humanoid")
while true do
local headToNPC = (NPC:WaitForChild("HumanoidRootPart").Position - Head.Position).Unit
local headLook = Head.CFrame.LookVector
local dotProduct = headToNPC:Dot(headLook)
if dotProduct >= sightLimit then
Humanoid:TakeDamage(20)
end
task.wait()
end
end)
end)
1 comment
Use WorldToViewportPoint to first check if it's on-screen at all, and then raycast from that position toward the object to see if it hits anything. If both checks pass then the player is looking at the part