Game Development / Game AI and NPC Development

Creating Dynamic NPC Behavior

In this tutorial, we'll look at how to create dynamic and intelligent NPC behavior. You'll gain a deeper understanding of advanced game AI techniques.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores the implementation of Artificial Intelligence (AI) in games to control NPC behavior and game mechanics.

Creating Dynamic NPC Behavior

Introduction

Goal

This tutorial aims to guide you through the process of creating dynamic and intelligent Non-Player Character (NPC) behavior for games. The focus will be on designing AI that makes your NPCs appear more life-like and responsive.

Learning Outcomes

By the end of this tutorial, you'll have a deeper understanding of advanced game AI techniques, specifically how to:
- Implement basic NPC behaviors
- Create dynamic and adaptable AI
- Use decision trees and state machines

Prerequisites

This tutorial assumes you have basic knowledge of:
- Programming (preferably in C#)
- Game development with Unity

Step-by-Step Guide

Implementing Basic NPC Behaviors

NPCs need to be able to perform basic tasks such as moving around the game world, interacting with other characters or objects, and responding to player actions.

// This is a simple NPC behavior script in Unity C#
public class NPC : MonoBehaviour 
{
    public float speed = 2.0f;
    private Vector3 target;

    void Start() 
    {
        target = transform.position;
    }

    void Update() 
    {
        if (Input.GetMouseButtonDown(0)) 
        {
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.z = transform.position.z;
        }

        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
    }
}

Creating Dynamic and Adaptable AI

A more advanced AI should be able to adapt to changing situations, making decisions based on current circumstances.

// This is a more advanced NPC behavior script in Unity C#
public class AdvancedNPC : MonoBehaviour 
{
    public float speed = 2.0f;
    private Vector3 target;
    private bool fleeing = false;

    void Start() 
    {
        target = transform.position;
    }

    void Update() 
    {
        if (fleeing) 
        {
            // The NPC is fleeing, so move away from the target
            transform.position = Vector3.MoveAwayFrom(transform.position, target, speed * Time.deltaTime);
        } 
        else 
        {
            // The NPC is not fleeing, so move towards the target
            transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
        }
    }

    void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.CompareTag("Player")) 
        {
            // The player has been spotted, so start fleeing
            fleeing = true;
            target = other.transform.position;
        }
    }

    void OnTriggerExit(Collider other) 
    {
        if (other.gameObject.CompareTag("Player")) 
        {
            // The player has left, so stop fleeing
            fleeing = false;
            target = transform.position;
        }
    }
}

Code Examples

Here are some code examples demonstrating how to implement NPC behavior.

Example 1: Basic Movement

// This code snippet shows how to make an NPC move towards a target position
public class NPC : MonoBehaviour 
{
    public float speed = 2.0f;
    private Vector3 target;

    void Start() 
    {
        target = transform.position;
    }

    void Update() 
    {
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
    }
}

Example 2: Interacting with the Player

// This code snippet shows how to make an NPC interact with the player
public class NPC : MonoBehaviour 
{
    void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.CompareTag("Player")) 
        {
            // The player has been spotted
            Debug.Log("Player spotted!");
        }
    }
}

Summary

In this tutorial, you've learned how to create basic NPC behaviors, make your NPCs respond dynamically to the player and other game events, and how to use decision trees and state machines to control NPC behavior.

Practice Exercises

  1. Create an NPC that follows the player around the game world.
  2. Make an NPC that can switch between different behaviors based on the player's actions.
  3. Design a group of NPCs that work together to achieve a common goal.

We hope you found this tutorial helpful. As next steps, consider exploring more advanced AI techniques such as pathfinding, behavior trees, and machine learning. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help