Unity Basic Course: Pathfinding Artificial Intelligence

In game development, pathfinding AI plays a role in allowing each game object that can move to understand the environment and efficiently find a path towards a given goal. In this course, you will learn the fundamental principles and implementation methods of pathfinding AI using the Unity engine. Through this course, we will explore how to build practical pathfinding AI using basic AI concepts and Unity’s NavMesh system.

1. What is Pathfinding AI?

Pathfinding AI is a form of artificial intelligence that autonomously allows an object to move to its destination by calculating the optimal path (either many-to-many or single) based on the starting position and goal position in a given environment (map). It is commonly used in games and robotics, playing a crucial role in solving complex pathfinding problems.

1.1. The Necessity of Pathfinding

In a game environment, pathfinding AI is essential when NPCs (Non-Player Characters) or player’s assisting characters need to navigate around obstacles to reach a designated goal. For example, pathfinding algorithms are used when enemies track the player or allies move to specific points.

2. Introduction to Unity’s NavMesh System

NavMesh, a powerful tool for implementing pathfinding AI in Unity, helps calculate various paths and allows characters to move appropriately. NavMesh is a pre-calculated network of paths that enables game objects to move freely.

2.1. Features of NavMesh

  • Pathfinding based on a navigation mesh
  • Handling obstacles in the surrounding environment
  • Real-time dynamic obstacle handling
  • Accessible via a simple API

2.2. Setting Up NavMesh in Unity

  1. After creating a project, build the necessary environment.
  2. Add the ‘NavMesh Obstacle’ component to the objects where NavMesh will be applied.
  3. Open the ‘Navigation’ panel in the Unity editor, and select the Bake menu to redraw.
  4. Add the ‘NavMesh Agent’ component to the character that will be used as an ‘Agent’.

3. Implementing Pathfinding AI

Now, we will write the following script in Unity to implement pathfinding AI that can be used in actual games.

3.1. Setting Up NavMesh Agent

NavMesh Agent is AI that allows a character to move toward the target point along the NavMesh. Here is a basic example of a NavMesh Agent script:

using UnityEngine;
using UnityEngine.AI;

public class AIFollow : MonoBehaviour
{
    public Transform target; // Target point
    private NavMeshAgent agent;

    void Start()
    {
        agent = GetComponent(); // Get the NavMeshAgent component
    }

    void Update()
    {
        if(target != null)
        {
            agent.SetDestination(target.position); // Move to the target point
        }
    }
}

3.2. Setting the Target Point

The target point can be set by the user clicking in the game or specifying a particular object. The method for setting the target point via user input is as follows:

void Update()
{
    if (Input.GetMouseButtonDown(0)) // On left mouse button click
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            target.position = hit.point; // Set the target point to the clicked position
        }
    }
}

4. Applying Obstacle and Evasion Techniques

To make the pathfinding AI more realistic and natural, obstacle evasion techniques are necessary. Unity’s NavMesh can recognize dynamically generated obstacles and help the character avoid them effectively.

4.1. NavMesh Obstacle

Dynamic obstacles are objects that can change position while moving. To accommodate this, the NavMesh Obstacle component should be applied, and the ‘Carve’ option can be activated to allow NavMesh to recognize and navigate around the obstacle.

4.2. Evasion Algorithm

By adding a simple evasion algorithm, the character should be able to recognize and avoid surrounding obstacles while moving toward the user-defined target point. Additional logic can be written as follows:

void AvoidObstacles()
{
    RaycastHit hit;
    if (Physics.Raycast(transform.position, agent.velocity.normalized, out hit, 1f))
    {
        if (hit.collider != null && hit.collider.CompareTag("Obstacle"))
        {
            // Add evasion behavior when an obstacle is detected
            Vector3 avoidDirection = Vector3.Reflect(agent.velocity, hit.normal);
            agent.velocity = avoidDirection * agent.speed; // Adjust speed in the direction to avoid
        }
    }
}

5. Practical Example

Now, let’s create a simple practical example to complete the pathfinding AI based on what we’ve learned so far.

5.1. Requirements

Create a project with the following features:

  • Characters respond to user input and move to the target point
  • Artificial intelligence that avoids obstacles
  • Basic understanding of the game environment and three-dimensional space

5.2. Project Setup

Run Unity, create a new project, and set up a basic environment that includes trigger objects and colliders. Here, we will specifically set up the NavMesh to be used.

6. Conclusion

This course taught you the basic methods for implementing pathfinding AI in Unity. With the NavMesh system, you were able to implement obstacle avoidance and efficient pathfinding. Furthermore, you have gained a foundation to use this technology to implement AI for various game objects. Now, advance the AI design further to suit different types of games and apply complex algorithms.

7. Additional Materials and References

If you would like to delve deeper into the topics covered in this course, please refer to the materials below: