- Home /
Destroy object when not looking
How do i make it so that when a player rotates their view a certain amount (possibly rotation view like 180) an object will be destroyed.
basically im making an enemy chase a player, and if the player turns away i want the enemy to disappear (destroy)
thinkin maybe a ray cast... idk
Answer by sanmn19 · Jan 13, 2014 at 07:59 AM
You can try the OnBecameInvisible() method under MonoBehaviour. Attach this to the player. This is assuming the player is a first person view. If its a 2d view with the bot chasing the player, then you can check for the specific range of angle in Update() function and destroy the bot.
GameObject bot;
void OnBecameInvisible(){
Destroy( bot );
}
thanks for the quick reply. yes its a FPS. although in the update function how do i check the rotation? cos it would be the rotation of the camera in relation to the enemy.. thanks for putting it in C# too
Actually that script should be placed on the enemy itself. Because then it will be called as soon as the enemy is no longer being rendered by the camera.
So you can just do:
private void OnBecameInvisible()
{
Destroy( gameObject );
}
Or if you do not want the enemy to be destroyed that quickly, you could do a quick check in the update ins$$anonymous$$d to see if the enemy is behind or in front of the camera. This may work or not depending on the size of the enemy and the field of view of the camera.
private void Update()
{
if(fpsCamera.transform.InverseTransformPoint(transform.position).z < 0)
{
Destroy(gameObject);
}
}
This transform the point of the enemy into local space for the camera, then it is easy to check if the enemys z position is negative and therefore behind the camera.
Your answer
Follow this Question
Related Questions
Creating basic enemy animation and attacking 4 Answers
(C#) My enemy dosent take damage ScriptFix 1 Answer
How to make a Tron Light cycle Enemy AI Script ? 0 Answers
Enemy not following player. 2 Answers
get closest enemy 1 Answer