简体   繁体   中英

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 () {


}

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM