Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 3 years ago

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
* Also need to make sure the player is visible and not behind an object. LuaSwitch 9 — 3y

1 answer

Log in to vote
1
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
3 years ago

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
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! LuaSwitch 9 — 3y
Ad

Answer this question