Course contentsShow
← Unity Game Development
Lesson 539 of 8288. Artificial IntelligenceFree lesson

Configuring Field of View Cones

You will calculate dot products between vectors to restrict AI vision to a specific angular range in front of the character.

Mastering Field of View Cones with Dot Products

In this lesson, you will learn how to mathematically restrict an AI's vision to a cone-shaped field using the dot product to detect targets only within a specific angular range.

The Logic of the Dot Product

When checking if a player is within an AI's field of view (FOV), a simple distance check isn't enough; we need to account for direction. The dot product is the perfect tool for this because it measures the "alignment" between two normalized vectors: the AI’s forward direction and the direction toward the target.

The dot product of two normalized vectors results in a value between -1 and 1:

  • 1: The vectors are pointing in the exact same direction.
  • 0: The vectors are perpendicular (90 degrees).
  • -1: The vectors are pointing in exact opposite directions.

Implementing the Cone

To create a cone, we define a maximum angle (e.g., 45 degrees). We convert this angle into a "dot product threshold" using Mathf.Cos(angle * Mathf.Deg2Rad). If the dot product between the AI's forward vector and the target's direction vector is greater than or equal to this threshold, the target is inside the cone.

public bool IsInFieldOfView(Transform aiTransform, Transform target, float fovAngle)
{
    Vector3 directionToTarget = (target.position - aiTransform.position).normalized;
    float dotProduct = Vector3.Dot(aiTransform.forward, directionToTarget);
    
    // Convert FOV angle to a threshold value
    float threshold = Mathf.Cos(fovAngle * 0.5f * Mathf.Deg2Rad);
    
    // If dot product is greater than threshold, target is within the cone
    return dotProduct >= threshold;
}

Why This Matters

By calculating the dot product, you transform a generic "can the AI see the player" check into a directional cone. This prevents the AI from detecting players behind it, allowing you to create stealth-based gameplay or more realistic tactical behaviors where the AI must physically turn to face its target before it can identify it.

Key Takeaway: The dot product allows you to define a specific angular field of view by comparing the alignment of the AI’s forward vector against the target’s direction vector, returning true only when the target falls within your defined threshold.