In this lesson, you will learn how to distinguish between composite, decorator, and leaf nodes to build hierarchical decision-making structures for your AI.
While State Machines are excellent for discrete transitions, Behavior Trees excel at handling complex, hierarchical logic. A Behavior Tree is a directed tree structure that executes from a root node, traversing downwards through branches to decide which action to take. The "anatomy" of this tree relies on three specific node types:
1. Composite Nodes (The Organizers)
Composites control the flow of the tree by determining how child nodes are processed. A Selector node, for example, will try its children one by one until one succeeds (like checking for an enemy, then checking for a patrol path). A Sequence node, conversely, will continue only as long as its children succeed—perfect for a series of steps like "Find Key" -> "Unlock Door" -> "Enter Room."
2. Decorator Nodes (The Modifiers)
Decorators are nodes with exactly one child. They act as "wrappers" that alter the behavior of that child. Common examples include an Inverter (which turns a success into a failure) or a Repeater (which tells a child to run until it finishes or is interrupted). Think of them as the "logic gates" of your tree.
3. Leaf Nodes (The Action Takers)
Leaf nodes (or Tasks) are the terminal points of the tree. They do not have children and perform the actual logic, such as MoveToTarget or PlayAnimation.
// Conceptual structure of a simple Behavior Tree
// Selector: Try to attack, if not, try to patrol
Composite Selector {
Sequence AttackTarget {
Leaf IsEnemyInRange; // Check
Leaf ExecuteAttack; // Action
}
Leaf PatrolArea; // Fallback action
}
By nesting these types, you move away from monolithic, spaghetti-code state machines. Composites dictate the "flow," Decorators add "constraints," and Leaf nodes execute the "raw behavior." This hierarchical approach allows you to swap or extend complex AI behaviors without rewriting the entire logic chain.
Key Takeaway: Behavior Trees control AI through a hierarchy where Composite nodes dictate flow, Decorators modify outcomes, and Leaf nodes perform the final actions.