How to Make an NPC move when you aren't looking at it

Hello, I’m working on a game of mine, and I would like to make an enemy that only moves when you aren’t looking at it, however, I am unsure about how to accomplish this. I am aware that it involves raycasting, however, I don’t really understand how it works, even after going to Roblox’s page about it. I also am unsure about how it would work to check if you can’t see something.

Please help!

1 Like

General solution is to use Camera::WorldToScreenPoint, which returns whether a point in space is visible on the player’s camera. Just check if the head / some bounding box around the NPC is visible, and if it is, then don’t move.

If the game is first person only, you also have the option of doing this all on the server, under the assumption that the player’s character’s direction represents their look angle, you can calculate the angle of the player’s camera to the NPC and suggest whether the NPC is visible.

4 Likes

In the simplest way I can put it, You’ll want to get some data to help you solve this issue. The data you’d like to know is the position of the NPC, the direction the NPC is facing. You can get this from the NPC’s CFrame.

You’ll also want to know where the closest player is and the direction they are facing. You can get this through their CFrame also.

Now you’ll want to raycast from the NPC’s CFrame to the Player’s CFrame. You can check if you have a line of sight based on if the ray is able to hit the player or a part in between the NPC and the Player.

After that, you’ll want to find the difference in angle between the NPC’s LookVector and the Player’s LookVector. Once you have that you can check if the NPC is within the player’s FOV.

Alternatively, @DrKittyWaffles is an easier option if you don’t want to handle all of the math. :grinning_face_with_smiling_eyes:

2 Likes