In this lesson, you will learn how to use physics-based raycasting to determine if an AI agent can visually verify the player’s presence in the game world.
While our Behavior Trees handle the "decision-making" logic, the AI needs a way to sense the physical environment. Geometric Line of Sight (LoS) detection is the bridge between the physical world and your AI brain. Instead of assuming the player is visible just because they are within a certain distance, we use a Raycast to verify that no walls, pillars, or other obstacles are blocking the agent's view.
The Raycasting Logic
To implement this, imagine an invisible laser beam originating from the AI’s eyes (or the center of its transform) and projecting toward the player’s position. If that beam hits the player’s collider before hitting any environmental colliders, the AI has "Line of Sight."
Here is a conceptual implementation you can place inside a custom Condition Node or Action Node:
public bool HasLineOfSight(Transform target, float maxRange, LayerMask obstacleMask)
{
Vector3 directionToPlayer = (target.position - transform.position).normalized;
float distanceToPlayer = Vector3.Distance(transform.position, target.position);
if (distanceToPlayer <= maxRange)
{
RaycastHit hit;
// Cast a ray from the AI to the player
if (Physics.Raycast(transform.position, directionToPlayer, out hit, maxRange, ~obstacleMask))
{
// Return true if the ray hit the player's collider
return hit.transform == target;
}
}
return false;
}
Critical Considerations
When implementing this, ensure your LayerMask is correctly configured. You typically want the raycast to ignore the AI’s own collider (otherwise, it might block its own sight) and potentially ignore triggers that aren't physical walls. Also, consider the origin point: casting from the AI's "head" rather than its "feet" prevents the AI from being blinded by small obstacles near the ground.
By integrating this into your Blackboard system, you can update a boolean variable—like isPlayerVisible—which your Behavior Tree can then use as a condition to transition from an "Idle" or "Patrol" state into a "Chase" or "Attack" state.
Key Takeaway: Geometric Line of Sight uses a physical raycast to confirm visual clarity between entities, transforming raw spatial data into a reliable trigger for your AI state transitions.