How would you make NPCs have a limited view distance?

I’ve been trying to make an NPC that shoots a rocket at the player, using Raycasting. The one problem I have is that I can’t find a way to make it so this NPC wouldn’t be able to ‘see’ the player if he were behind him or otherwise outside of a limited field of view. How could I go about accomplishing this?

3 Likes

I believe you could use Region3 where if the player is inside the part the NPC would shoot at the player.

1 Like

Dot product is a great example of this and is frequently used to create this result.

It is called field of sight/view.

Here is a tutorial on one:

And video on one.

Dot product is part of linear math so if you don’t know it, there is also a vector mathematics tutorial tutorial that should have it.

You get two Vector3s then dot on one with the other Vector3 as a parameter;
v3:Dot(otherv3) (order does not matter)

In a nutshell, a straightforward way to do this is to use the NPC’s head part’s CFrame.LookVector as the direction the NPC is looking, and take the dot product with the vector given by (player Head position - NPC Head position). If the dot product is negative, the player is behind the NPC. In this simplified example, the NPC’s field of view id a perfect hemisphere in the direction their head is facing. And of course you can check line of sight to other body parts of the player as well, I just used the head as an example.

To fine tune this–e.g. to give the NPC a narrower or wider field of view, or to make vertical field of view different from horizontal–requires good understanding of exactly what the vector dot product represents, geometrically, and will require some reading and experimentation as others have noted already.

1 Like

I appreciate the help - as someone who is quite a stranger to more advanced mathematics like ‘dot products’, it means a lot.

NP. Another way to describe the example I gave you, is that it uses the dot product to answer the question: “Would my NPC have to turn their head more than 90 degrees in order to look directly at the player”. The dot product of two vectors at right angles is 0. It’s positive if the included angle is less than 90 degrees, and negative if it’s more than 90. So it’s convenient way to calculate if some vector is within 90 degrees of another. And 90 degrees in any possible direction away from where the NPC is currently looking has the total solution space of a hemisphere (with radius the length of your Ray).