I have a script that checks whether the player is in line of sight of an enemy using raycasting, however I always want to only return true if the player is in front of the enemy. How would I do that.
Calculate the angel between your forward vector and the enemy position. If absolute value is bigger than a certain threshold (eg. 90 degrees) it's behind you. To do that there a some very convenient functions:
Vector3 directionToTarget = transform.position - enemy.position;
float angel = Vector3.Angel(transform.forward, directionToTarget);
if (Mathf.Abs(angel) > 90)
Debug.Log("target is behind me");
Not tested but should work.
See this answer, except use Z instead of X.
I know it’s been a month since any comments were left on this, but posting as the link in the answer no longer works. So regarding spree 1’s code above, for complete 360 degree detection, I think it should be;
if (Mathf.Abs(angel) > 90 && Mathf.Abs(angel) < 270)
Debug.Log("target is in front of me");
if (Mathf.Abs(angel) < 90 || Mathf.Abs(angel) > 270)
Debug.Log("target is behind me");
Check out InverseTransformPoint as mentioned, but placing code here for better reference:
public Transform cam;
public Vector3 cameraRelative;
void Start()
{
cam = Camera.main.transform;
Vector3 cameraRelative = cam.InverseTransformPoint(transform.position);
if (cameraRelative.z > 0)
print("The object is in front of the camera");
else
print("The object is behind the camera");
}