How to check if the player is in the field of view of the monster?

Thank you!

I figured it out and designed my own playground just to confirm that I got it. https://playground.babylonjs.com/#Z3JGUX

My playground actually implements several related mechanics.

  1. function lookAtPoint makes mesh to turn and to look at the provided point.

  2. function isInFov checks if something is in FOV of provided parameters. Function accepts fovDirection - the direction from the center of FOV, fovAngle - angle in radians, directionToTarget - direction to the target from the center of FOV of the interest.
    fovDirection and directionToTarget should be pre-computed, however in real-life scenarios the direction of the monster can be a property in the monsterInstance class (especially if monster movements are implemented already), so that value can be read directly. In my playground I compute it manually based on the point where the monster is looking at.

  1. function checkIfPlayerIsVisible checks if the player is in the FOV and there are no obstacles between player and monster (like a wall). Helper function getClosestHit also accepts an array of exceptions, that should not be counted as blockers. For example monster’s own mesh and any objects assumed as transparent like glass windows or floating medkits, etc.
  2. MultiMaterial example (bonus). I needed to represent monster’s face somehow, so I choose that way.

The downside of the approach is that the player is visible only if it’s origin (registration point) is visible. So, if the player is very wide and part of it is in FOV, but not the origin, then the player is considered as not visible. Workaround: additionally, to player’s origin calculate directions to all player vertices and check them. If the number of vertices is big, the bounding box can be used (8 vertices). This approach still can be exploited though, for example if all vertices are covered and only some central part of edges/faces is visible. But in my opinion for first person shooters we can just use player camera origin, because if NPC can see the player and the player can’t see him (even if player turns the head to the right direction) it’s a bit frustrating.

1 Like