Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to see if NPC has a player in its Field of View?

I've searched far and wide and can't seem to find any solution to this. I'm trying to make an NPC that you try to hide from and I want to make it where it will detect you if you travel within its set FOV and within a certain distance.

Image Example: Image

I want something that is entirely server-side, I can do with clientside, but I want to avoid clientside checking as much as possible.

I've seen people recommend RayCasting but I can only get it to cast in one straight line and not in a FOV (Field Of View) like I'm attempting to.

Any ideas?

1 comment

1
  • Also need to make sure the player is visible and not behind an object.

1 answer

✓ Accepted answer

You can use the dot product, which is the scalar projection of one vector onto another, basically takes two vectors and returns a number. You can get the angle from a dot product by doing math.acos(dot / (a.Magnitude * b.Magnitude).

So, what you'd need is the direction the NPC is looking and the direction of the NPC to a player and calculate the angle and see if the angle is in a specified range:

local look = NPC.LookVector
local facing_direction = (HumanoidRootPart.Position - NPC.Position).Unit
local dot = look:Dot(facing_direction)
local angle = math.deg( math.acos(dot) )

if angle <= 80 then
    -- in range
end

1 comment

1

While this unfortunately doesn't solve the problem of checking if the player is visible, it does check for the player in its FOV. After this, its a simple raycast for the rest. Cheers!

This discussion is preserved as it was. New answers, comments, and votes are closed.