RebDev
RebDev

Reputation: 335

Finding the angle of an GameObject compared to another

I have two objects, one is the player and the other is an Enemy. I need to know if the Enemy is facing away, towards etc the Player. The direction that the Player is facing makes no difference to me. Any help would be greatly appreciated.

// Both variables set in the inspector
public GameObject theEnemy;
public GameObject thePlayer;

void Update () {


}

Upvotes: 0

Views: 1748

Answers (1)

Smilediver
Smilediver

Reputation: 1818

Basically what you want to do is to find an angle between two vectors:

Vector3 enemyLookDirection = enemy.transform.forward;
Vector3 playerRelativeDirection = 
    (player.transform.position - enemy.transform.position).normalized;

float angle = Vector3.Angle(enemyLookDirection, playerRelativeDirection);
float enemyFov = 45.0f; // Biggest angle that enemy can see from the center of view
if (angle < enemyFov)
    EnemyCanSeePlayer();

P.S. instead of using transform.position, you might want to calculate position of player's and enemy's eyes.

Upvotes: 1

Related Questions