Hey Unitarians!
I have made an AI aircraft and it follows the player nicely and it can shoot, but I want to restrict its shooting to only when it can see the player. By seeing the player I mean when the player is in front of it.
I know people would use Physics.Linecast() but the problem is that the AI plane can only shoot at the player if the player is right in front of the plane. The distance doesn’t matter, but the player has to be in front of the AI aircraft. How would I do this?
‘Front’ can mean different things. Here are two solutions.
Vector3 dir = player.position - transform.position;
if (Vector3.Angle(dir, transform.forward) < someAngle) {
Debug.Log("I can fire on the player");
}
This will give you a cone where ‘90’ for ‘someAngle’ will be anywhere in forward of the AI.
Here is another:
Vector3 pos = transform.InverseTransformPoint(player.position);
if (pos.z > 0.0f) {
Debug.Log("I can fire on the player");
}
‘pos.z’ is the ‘z’ distance in front of the plane. Other values that 0.0 can be used, but note that the localScale of the transform will effect the ‘z’ value.