I know this is old but maybe this will help someone as it did for me. This post helped me go in the right direction. Below is a method I wrote for a 2D game. This is set for object orientation of my game so may have to play with parameters for your game. (I have Y forward, X right -it’s a top down game)
bool IsLookingATObject(Transform obj, Transform targetObj)
{
//direction of the target as a vector
Vector3 direction = targetObj.position - obj.position;
float ang = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
//current angle in degrees
float anglecurrent = obj.eulerAngles.z;
float checkAngle = 0;
//Checking to see what quadrant current angle is at
if (anglecurrent > 0 && anglecurrent <= 90)
{
checkAngle = ang - 90;
}
if (anglecurrent > 90 && anglecurrent <= 360)
{
checkAngle = ang + 270;
}
//If current angle is equal to the angle that I need to be at to look at the object, return true
//It is possible to do "if (checkAngle == anglecurrent)" but some times you don't get an exact match so do something like below to have some error range.
if (anglecurrent<= checkAngle+0.5f && anglecurrent >= checkAngle - 0.5f)
{
return true;
}
else
return false;
}
public Transform other;
private bool IsFacingObject(){
// Check if the gaze is looking at the front side of the object
Vector3 forward = transform.forward;
Vector3 toOther = (other.transform.position - transform.position).normalized;
if(Vector3.Dot(forward, toOther) < 0.7f){
Debug.Log("Not facing the object");
return false;
}
Debug.Log("Facing the object");
return true;
}
you can check if two objects facing one another easily by using Dot product between them. the result in the case of facing each other is -1. then check if the angle between your agent and target is bigger than 0 or 7 deg as a threshold.
e.g
if (Vector3.Dot(rb.velocity.normalized, targetRb.velocity.normalized) == -1)
{
if (Vector3.Angle(playerRigidbody.velocity, targetRigidbody.velocity) <= 7)
{ // the facing each other }
}