How to check if a monster can see player or player can see monster

Hello,

I want to check if a monster can see player or player can see monster using OnBecameVisible() but it always shows me that enemy is visible even if it is behind the wall.
I looked on google where the only answer is Raycasting, but it only shoots on ray in center of camera so not only visible but in direct line of sight.

Is there a way to check if its visible without Raycasting?

Also I’m using different Layers so that monster cant see himself.

1 Like

You should really use Raycasting, maybe multiple ones to different points on bodies of your monster and player. OnBecameVisible, as I understand, returning true when it’s gameobject renderer is rendered by any camera. Monster don’t even have a camera to look at the player! And player’s camera, without properly baking up occlusion culling, would see stuff through walls. Yeah, by default all renderers are being rendered inside camera FoV, even if they are being hidden behind other objects.

I never needed to implement such system so may be wrong, but I would do something like making several empty GameObjects representing the edge/corner points for a monster and for a player, add like 2 raycast shooting GameObject points for monster’s eyes (2 is probably overkill) so each of them cast rays to all player edge points, and even if one hit, it sees you. And vice versa, if you need to be sure that player see the enemy even slightly, shoot racyasts to all monster points, not just from the camera center but from several gameobjects which are inside the camera box, like 4 on edges, and I assume one from camera center.

That being said this is probably overly precise and not very optimal. I would add some optimizations like to shoot raycasts only if the monster is rendered by camera, and at adequate range, and same goes for the monster, only shoot raycasts from it if the player is in it’s field of view (checking angle here) and at adequate distance.