Chapter 10: Game AI Fundamentals
In this chapter, we'll delve into the foundational concepts of artificial intelligence (AI) in game development using C++. We'll explore basic AI behaviors, understand how to manage AI states using state machines, introduce pathfinding algorithms like A, and learn how to script AI decisions. By the end of this chapter, you'll have the knowledge to implement enemy AI in a platformer game, where enemies patrol platforms and chase the player upon detection.*
Table of Contents
- Introduction to Game AI
- Simple AI Behaviors
- State Machines
- Pathfinding Basics
- Scripting AI Decisions
- Project Example: Enemy AI in a Platformer
- Summary
- Exercises
Introduction to Game AI
Game AI is the simulation of intelligent behaviors in non-player characters (NPCs) to provide a challenging and entertaining experience for the player. Unlike traditional AI, game AI focuses on creating believable and fun interactions rather than solving complex problems optimally.
Simple AI Behaviors
In game development, breaking down AI into simple, modular behaviors makes it easier to manage and extend. Let's explore common behaviors: patrol, chase, and flee.
Patrol Behavior
Patrolling is when an AI character moves along a predefined path or between waypoints.
Implementation Steps:
- Define Waypoints: Set positions in the game world that the AI will move to sequentially.
- Movement Logic: Move the AI from one waypoint to the next.
- Direction Handling: Ensure the AI faces the correct direction when moving.
Example Code:
class EnemyAI {
public:
std::vector<Vector2> waypoints;
int currentWaypointIndex = 0;
float speed = 100.0f;
void Update(float deltaTime) {
Vector2 target = waypoints[currentWaypointIndex];
MoveTowards(target, deltaTime);
if (PositionReached(target)) {
currentWaypointIndex = (currentWaypointIndex + 1) % waypoints.size();
}
}
void MoveTowards(Vector2 target, float deltaTime) {
Vector2 direction = Normalize(target - position);
position += direction * speed * deltaTime;
}
bool PositionReached(Vector2 target) {
return Distance(position, target) < threshold;
}
};
Chase Behavior
Chasing involves the AI pursuing the player when certain conditions are met (e.g., within a detection radius).
Implementation Steps:
- Detection Logic: Check if the player is within a certain range.
- Chase Movement: Move the AI towards the player's position.
- Transition Conditions: Define when to stop chasing (e.g., player escapes detection range).
Example Code:
float detectionRadius = 200.0f;
void Update(float deltaTime, Vector2 playerPosition) {
float distanceToPlayer = Distance(position, playerPosition);
if (distanceToPlayer < detectionRadius) {
// Chase the player
MoveTowards(playerPosition, deltaTime);
} else {
// Patrol as usual
Patrol(deltaTime);
}
}
Flee Behavior
Fleeing is when the AI moves away from the player, often used for passive or scared entities.
Implementation Steps:
- Threat Detection: Identify when the AI should flee (e.g., player is too close).
- Flee Movement: Move the AI away from the player's position.
- Safety Check: Determine when it's safe to stop fleeing.
Example Code:
void Update(float deltaTime, Vector2 playerPosition) {
float distanceToPlayer = Distance(position, playerPosition);
if (distanceToPlayer < fleeRadius) {
// Flee from the player
Vector2 direction = Normalize(position - playerPosition);
position += direction * speed * deltaTime;
}
}
State Machines
AI behaviors often need to switch between different states (e.g., patrolling, chasing). State machines help manage these states and transitions efficiently.
Understanding States and Transitions
- States: Represent the current behavior of the AI.
- Transitions: Conditions under which the AI switches from one state to another.
Implementing a Finite State Machine in C++
State Enumeration:
enum class AIState {
Patrol,
Chase,
Flee
};
State Handling:
class EnemyAI {
public:
AIState state = AIState::Patrol;
void Update(float deltaTime, Vector2 playerPosition) {
switch (state) {
case AIState::Patrol:
Patrol(deltaTime);
if (CanSeePlayer(playerPosition)) {
state = AIState::Chase;
}
break;
case AIState::Chase:
Chase(playerPosition, deltaTime);
if (!CanSeePlayer(playerPosition)) {
state = AIState::Patrol;
}
break;
case AIState::Flee:
Flee(playerPosition, deltaTime);
break;
}
}
};
Transition Functions:
bool CanSeePlayer(Vector2 playerPosition) {
float distanceToPlayer = Distance(position, playerPosition);
return distanceToPlayer < detectionRadius;
}
Pathfinding Basics
For AI to navigate complex environments, simple movement towards a target isn't sufficient. Pathfinding algorithms help find the best path around obstacles.
Introduction to Pathfinding Algorithms
- Graph Representation: The game world is represented as a graph of nodes (waypoints) connected by edges (paths).
- Pathfinding: Algorithms like A* find the shortest path between nodes.
The A* Algorithm Explained
A* combines features of Dijkstra's algorithm and greedy best-first search to efficiently compute the shortest path.
Key Components:
- Open List: Nodes to be evaluated.
- Closed List: Nodes already evaluated.
- Cost Functions:
- g(n): Cost from the start node to node n.
- h(n): Heuristic estimated cost from node n to the goal.
- f(n): Total estimated cost (f(n) = g(n) + h(n)).
Basic Steps:
- Add the start node to the open list.
- While the open list is not empty:
- Find the node with the lowest f(n).
- Move it to the closed list.
- For each neighbor:
- If in closed list, skip.
- Calculate f(n).
- If not in open list or better path found, update and add to open list.
Scripting AI Decisions
Beyond basic behaviors, AI can make more complex decisions using scripting techniques.
Decision Making in AI
- Decision Trees: Hierarchical models representing decisions and their possible consequences.
- Behavior Trees: Control flow structures organizing actions in a tree.
Implementing Decision Trees in C++
Decision Node Structure:
class DecisionNode {
public:
virtual void MakeDecision(EnemyAI& ai) = 0;
};
class IsPlayerVisible : public DecisionNode {
public:
DecisionNode* trueNode;
DecisionNode* falseNode;
void MakeDecision(EnemyAI& ai) override {
if (ai.CanSeePlayer()) {
trueNode->MakeDecision(ai);
} else {
falseNode->MakeDecision(ai);
}
}
};
class PatrolAction : public DecisionNode {
public:
void MakeDecision(EnemyAI& ai) override {
ai.state = AIState::Patrol;
}
};
class ChaseAction : public DecisionNode {
public:
void MakeDecision(EnemyAI& ai) override {
ai.state = AIState::Chase;
}
};
Building the Tree:
IsPlayerVisible* root = new IsPlayerVisible();
root->trueNode = new ChaseAction();
root->falseNode = new PatrolAction();
Using the Decision Tree:
void UpdateAI(EnemyAI& ai) {
root->MakeDecision(ai);
ai.UpdateState();
}
Project Example: Enemy AI in a Platformer
Let's apply what we've learned by creating an enemy AI for a platformer game.
Setting Up the Enemy Character
Sprite and Animation:
- Load enemy sprites.
- Set up animations for idle, walk, and attack.
Enemy Class Structure:
class EnemyAI {
public:
Vector2 position;
AIState state;
std::vector<Vector2> patrolPoints;
// Other attributes
};
Creating Patrol Behavior
- Define patrol points along the platform.
- Implement movement between points.
void Patrol(float deltaTime) {
// Move towards the next patrol point
}
Implementing Chase Upon Detection
- Create a function to detect the player.
bool CanSeePlayer(Player& player) {
// Implement line of sight or proximity detection
}
- Modify
Update function to switch to chase state.
Testing and Refining the AI
- Run the game and observe enemy behavior.
- Adjust parameters like detection radius, speed, and patrol paths.
- Ensure smooth transitions between states.
Summary
In this chapter, we've covered the basics of implementing AI in games using C++. You've learned about simple AI behaviors like patrol, chase, and flee, and how to manage these using state machines. We've introduced pathfinding concepts and provided an overview of the A* algorithm. Additionally, we've explored how to script AI decisions using decision trees. The project example demonstrated how to apply these concepts to create an enemy AI in a platformer game.
Exercises
-
Extend the Enemy AI:
- Add a new state called
Attack, where the enemy attacks the player when close enough.
- Implement the logic for transitioning to and from the
Attack state.
-
Implement Flee Behavior:
- Modify the enemy AI to flee from the player when the player's health is above a certain threshold.
-
Integrate A Pathfinding:*
- Create a grid-based level and implement the A* algorithm for enemy pathfinding.
- Ensure the enemy can navigate around obstacles to reach the player.
-
Create a Behavior Tree:
- Implement a behavior tree for the enemy AI that includes patrolling, chasing, attacking, and fleeing behaviors.
-
Optimize AI Performance:
- Profile your AI code to find any performance bottlenecks.
- Optimize the code to run efficiently, especially when multiple AI agents are active.
By completing these exercises, you'll deepen your understanding of game AI and be better prepared to tackle more complex AI challenges in your future game development projects.