In this lesson, you will learn how to assign numerical weights to action costs so your AI planner prioritizes the most efficient, rather than just the shortest, sequence of behaviors.
The Role of Action Costs
When your AI uses A* Search for plan generation, it typically looks for the shortest path of actions to reach a goal. However, "shortest" isn't always "best." For example, an NPC might find two ways to get a potion: walk to the store and buy it (cost: 10) or steal it from a guard (cost: 50 due to risk). Without a heuristic cost, the AI might default to the path with the fewest steps, ignoring the danger or resource drain.
Implementing a Cost Function
To influence decision-making, we define a GetCost() function for our AtomicAction objects. This function returns a float representing the "expense" of performing that action, considering factors like time, risk, or stamina.
public abstract class AtomicAction
{
public float baseCost;
// Calculate cost based on current state
public virtual float CalculateCost(Blackboard blackboard)
{
float dynamicModifier = 0f;
// Example: Penalize actions that consume too much stamina
if (blackboard.GetFloat("Stamina") < 20f)
dynamicModifier += 50f;
return baseCost + dynamicModifier;
}
}
Balancing the Planner
When the planner evaluates a sequence of actions, it sums these costs. By adding a penalty to high-risk or low-efficiency actions within CalculateCost, you force the A* algorithm to favor paths with the lowest accumulated value.
For instance, you can integrate your Spatial Memory System data here: if an area is flagged as "dangerous" in your blackboard, increase the cost of any movement actions leading into that node. The planner will naturally "steer" the AI away from these zones during its initial search phase, selecting a path that might be longer in steps but significantly lower in "total cost."
By tuning these costs, you transform your AI from a simple goal-seeker into a strategic decision-maker that weighs the consequences of its every move.
Key Takeaway: By assigning dynamic costs to your atomic actions, you enable your planner to weigh situational factors like risk, fatigue, or time, ensuring the AI chooses the most intelligent path rather than just the first valid one it finds.