简体   繁体   English

寻找一个GameObject与另一个的角度

[英]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. PS,而不是使用transform.position,您可能想要计算玩家和敌人的眼睛的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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