- Home /
Trigger when something enters the Field of View of the Camera
Hi,
i want to trigger a script when an enemy enters the Field of View of a specific camera. The field of view of my player charcter. There are more cameras in the scene.
The only solution i found is to use a specific pyramid-like mesh und attach a mesh collider to it. (The mesh is the prop_cctvCam_collision from the Stealth Tutorial). That seems to work for now, but it feels clonky. Is there a better way to do something like this?
Thanks in advance
chef_seppel
Its very simple actually. Unity had a tutorial on this in the S$$anonymous$$lth Tutorial videoseries, regarding AI. You need to get the angle between the forward vector of your players camera and the enemy, and you can sortof check if the enemy is visible.
As you didn't mention that range or visibilty is a problem, the base code is very simple. Just call this whenever the enemy comes within range. Personally I used a spherecollider as a trigger as the range, and put this in my OnTriggerStay function:
direction = enemy.transform.position - transform.position; //Get direction from player to enemy
float angle = Vector3.Angle(direction, transform.forward); //Get the direction from player to 1 unit forwards and calculates the 3D angle of the two directions.
float fov = camera.FieldOfView(); //Writing this from the back of my head. Something like that.
if(angle < fov * 0.75F) {
//*0.75f works precisely if your enemy is exactly .5 units wide. I dont know the proper mathematical calculations, sorry.
DoSomething();
return;
}