i want to do like a npc fov, like detecting if another npc/player goes into the fov
ive been trying the dot product but its confusing me, i want it to detect if a player/npc is in the fov
something like this
with the cone being the fov
ive been trying for about 3 days now, if anyone could help i would appreciate it
the best way is not to use “lots o’ raycasting” because that’s very bad for performance and sometimes not effective. Instead he should just use the dot product and loop through all players/npcs and also a ray to detect if there’s a wall.
Edit: If a player leaves, any other code you add to this script may break (Kind of obvious but just want to clarify for any new scripters who may stumble across this post)
@incognitobot_rblx 's works but you I you might have to change the value depending on how much you want your npc to see. :Dot() goes from -1 to 1, so if you want to have say 70 degrees of fov, you would have this (Code goes inside npc. You can undo the comments on the prints if you want a visual output, but you can also use the “playersseen” table to detect which players are in the npc’s fov. Note that this code does not care about range.):
local rs = game:GetService("RunService")
local npc = script.Parent
local npcfov = 70
local playersseen = {}
print(0.5 - (npcfov/2)/100)
print(0.5 + (npcfov/2)/100)
print(1-(1/90 * npcfov/2))
--Explaination:
--NOTE THAT THE "NPCFOV" MAY NOT BE TRUE FOV, BECAUSE I HAVE NO IDEA HOW IT WORKS LOL
--THE "NPCFOV" IS JUST THE AMOUNT OF "DEGREES" THE NPC CAN SEE
--When the player is right in front of the npc (90 degrees), the dot product returns 1
--As it approaches 0 and 180 degrees, the dot product goes toward 0
--Hence in order to get the 70 degrees of fov, you first need to find the conversion for the degrees
--Then you multiply it by half of the fov (half for each side)
--We should now get the converted value of 35 degrees (if npcfov is 70)
--Next, we subtract by 1 because we need to get 35 degrees from the "straight ahead"
--Ik my explaination is not very good, so if anyone has a better explaination feel free to reply to my post
rs.Heartbeat:Connect(function()
local head = npc:WaitForChild("Head")
local npclv = head.CFrame.LookVector
for _, player in pairs(game.Players:GetPlayers()) do
local character = player.Character
if character then
local npctoplayer = (character:WaitForChild("Head").Position - head.Position).Unit
local dotproduct = npctoplayer:Dot(npclv)
--print(dotproduct)
if dotproduct > 1-(100/90 * npcfov/2)/100 then
--print("In FOV")
if not table.find(playersseen, player) then
table.insert(playersseen, player)
end
else
--print("Off FOV")
if table.find(playersseen, player) then
table.remove(playersseen, table.find(playersseen, player))
end
end
else
--print("Off FOV")
if table.find(playersseen, player) then
table.remove(playersseen, table.find(playersseen, player))
end
end
end
end)