Consulting, services, computer engineering. Implementation of technology solutions and support for businesses.

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

Windows 11 v26100 test with a Csharp First FPS: Artificial intelligence to enemy patrol

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol gif

 

Windows 11 v26100 test with a Csharp First FPS: Artificial intelligence to enemy patrol

 

 

Who am i / About the author...

ident021 180 facebook linkedin insider mcp learn metadatas sans cravate 128x128 autocolors 18052006 191123 mcse microsoft logomcsa microsoft logomcdba logo

since 2001, Insider since 2014.

 

Thanks to Microsoft EMEA GBS to let me participate in the year 2014 to the Insider project during my work. Then, This Windows test project, here in version 11, is based on the cycle of the insider Preview Builds, now in the Dev Channel: it is fun to test the new features. I can learn new features, validate them and share them with you :-)

Why game engines? Because as a system/network/database developer I only see consoles and screens with unfunny and ugly text. With game engines i can show you colors and animations, that's more fun and more eye-catching :)

This tutorial is made in a test environment, for pleasure and not to earn money. It is a non-profit project. It shows that the concept is possible, for a demontration, artistic, or educational purposes, school learning course. Don't test in a real environment in production. 

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : last articles

 

 

how to install Godot engine

Windows 11 v23619 testing with a Unity game engine Hello World

How to use signals with Godo Engine (Red bouncing ball)

A Paddle Game with Godot engine

Windows 11 v26058 C Sharp with Copilot Godot Engine multiplayer client server POC

Windows 11 v26080 Blender installation

Windows 11 v26100 Csharp First FPS building the level

Windows 11 v26100 Csharp First FPS creating a health pickup

Windows 11 v26100 Csharp First FPS moving the player

Windows 11 v26100 Csharp First FPS Scripting camera behavior to follow the player

Windows 11 v26100 Csharp First FPS Player is shooting bullets

Windows 11 v26100 Csharp First FPS; GUI graphical user interface and win condition

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : goal

 

The goal of this chapter is to bring to the enemy an artificial intelligence, so that he can walk around the arena, patrol between coordinates to seek for the player, and choose himself his path to ovoid the turrets.

Components comes as standard with Unity.

A NavMesh is essentially a map of the walkable surfaces.

If a NavMesh is the level map, then a NavMeshAgent is the moving piece on the board.

Adding NavMeshObstacle components to those objects lets the system know that they need to be avoided.

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : how to

 

 

I’ll set up the Enemy Prefab as a NavMeshAgent, and getting the Enemy Prefab to

move along a predefined route in a seemingly intelligent way.

https://docs.unity3d.com/Manual/nav-CreateNavMeshObstacle.html

I select the Environment GameObject, click on the arrow icon next to Static in the Inspector window, and choose Navigation Static.

Interesting links:

https://forum.unity.com/threads/navigation-static.1411134/

//docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/whats-new.html" title="https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/whats-new.html" data-mce-href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/whats-new.html">https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/whats-new.html

https://learn.unity.com/search?k=%5B%22q%3ANavigation%22%5D

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : install the ai package

 

Change children when the dialog window pops up to set all the Environment child objects to Navigation Static ? Yes

 

I install the AI navigation package: i integrate an AI package ready to use.

https://docs.unity3d.com/2022.1/Documentation/Manual/Packages.html

If you’re looking for basic artificial intelligence with mathematics course, and so and so, check this out :

https://learn.unity.com/course/artificial-intelligence-for-beginners

https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.0/manual/index.html

Window > Package Manager

I click on Unity registry > + add package by name

com.unity.ai.navigation

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol add package ai navigation

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : bake

 

i set « static » the floor and the four planes. 

Menu Windows/AI/Navigation/Bake tab

I click on the « bake » button.

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol bake button

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : add nav mesh agent

 

I select the Enemy Prefab in the Prefabs folder, click Add Component in the Inspector window, and search for NavMesh Agent, add.

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol add nav mesh agent

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : create the patrol route

 

Hierarchy/+Create empty and i name it Patrol_Route

I select Patrol_Route, click + | Create Empty to add a child GameObject, and rename it Location_1.

All the positions, player, enemy, patrol route, location_1… must be on the same neighboor coordinates, same plane, be careful of the bad coordinates else it won’t work as expected.

I Position Location_1 in one of the corners of the level

X=0.759 Y=-4 Z=-1.894

Enemy :

X=-1.968964 Y=-3 Z=11.33

Same thing for the 3 others locations at each corner of the arena.

I modify the the code EnemyBehavior.cs like this

 

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class EnemyBehavior : MonoBehaviour

{

    // declares a variable for storing the PatrolRoute empty parent GameObject

    public Transform PatrolRoute;

    // declares a List variable to hold all the child Transform components in PatrolRoute

    public List<Transform> Locations;

    void Start()

    {

        // call the InitializePatrolRoute() method when the game begins

        InitializePatrolRoute();

    }

  // procedurally fill Locations with Transform values

    void InitializePatrolRoute()

    {

        // foreach statement to loop through each child GameObject in PatrolRoute and reference its Transform component

        foreach(Transform child in PatrolRoute)

        {

            // add each sequential child Transform component to the list of locations using the Add() method as we loop through the child objects in PatrolRoute

            Locations.Add(child);

        }

    }

    //fired whenever an object enters the enemy’s Sphere Collider radius

    void OnTriggerEnter(Collider other)

    {

        // access the name of the colliding GameObject

        if (other.name == "Player")

        {

            Debug.Log("Player detected - attack!");

        }

    }

    // fired when an object leaves the enemy Sphere Collider radius

    void OnTriggerExit(Collider other)

    {

        //check the object leaving the Sphere Collider radius

        if (other.name == "Player")

        {

            Debug.Log("Player out of range, resume patrol");

        }

    }

}

 

 

I select Enemy in the Hierarchy window and drag the Patrol_Route object from the Hierarchy window onto the Patrol Route variable in EnemyBehavior

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol route to EnemyBehavior

 

I hit F5, play, and the locations populate

 

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy locations populate

 

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol :  moveToNextPatrolLocation() method

 

I modify the EnemyBehavior C# code like this

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// adds the UnityEngine.AI using directive so that EnemyBehavior has access to Unity’s navigation classes, in this case, NavMeshAgent
using UnityEngine.AI;

public class EnemyBehavior : MonoBehaviour
{

// declares a variable for storing the PatrolRoute empty parent GameObject
public Transform PatrolRoute;
// declares a List variable to hold all the child Transform components in PatrolRoute
public List<Transform> Locations;

// variable to keep track of which patrol location the enemy is currently walking toward
// Since List items are zero-indexed, we can have the Enemy Prefab move between patrol points in the order they are stored in Locations.
private int _locationIndex = 0;

// declares a variable to store the NavMeshAgent component attached to the Enemy GameObject. This is private because no other classes should be able to access or modify it
private NavMeshAgent _agent;

void Start()
{

// find and return the attached NavMeshAgent component to the agent
_agent = GetComponent<NavMeshAgent>();

// call the InitializePatrolRoute() method when the game begins
InitializePatrolRoute();


// calls the MoveToNextPatrolLocation()
MoveToNextPatrolLocation();

}

void Update()
{
/*
First, it declares the Update() method and adds an if statement to check whether two
different conditions are true:
remainingDistance returns how far the NavMeshAgent component currently is from its set destination, so we’re checking if that is less than 0.2
pathPending returns a true or false Boolean, depending on whether Unity is computing a path for the NavMeshAgent component

*/
if (_agent.remainingDistance < 0.2f && !_agent.pathPending)
{
// If _agent is very close to its destination, and no other path is being computed, the if statement returns true and calls MoveToNextPatrolLocation().
MoveToNextPatrolLocation();
}
}

void MoveToNextPatrolLocation()
{

// If Locations is empty, we use the return keyword to exit the method without continuing.
if (Locations.Count == 0)
return;

/*
Finally, it declares MoveToNextPatrolLocation() as a private method and sets _agent.destination:
• destination is a Vector3 position in 3D space
• Locations[_locationIndex] grabs the Transform item in Locations at a given index
• Adding .position references the Transform component’s Vector3 position
*/
_agent.destination = Locations[_locationIndex].position;


// increment the index from 0 to 4 and then restart it at 0 so that our Enemy Prefab moves in a continuous path
_locationIndex = (_locationIndex + 1) % Locations.Count;

}

// procedurally fill Locations with Transform values
void InitializePatrolRoute()
{
// foreach statement to loop through each child GameObject in PatrolRoute and reference its Transform component
foreach (Transform child in PatrolRoute)
{
// add each sequential child Transform component to the list of locations using the Add() method as we loop through the child objects in PatrolRoute
Locations.Add(child);
}
}


//fired whenever an object enters the enemy’s Sphere Collider radius
void OnTriggerEnter(Collider other)
{
// access the name of the colliding GameObject
if (other.name == "Player")
{
Debug.Log("Player detected - attack!");
}
}
// fired when an object leaves the enemy Sphere Collider radius
void OnTriggerExit(Collider other)
{
//check the object leaving the Sphere Collider radius
if (other.name == "Player")
{
Debug.Log("Player out of range, resume patrol");
}
}
}

 

I hit Play F5, and i watch the Enemy Prefab walk around the corners of the level in a continuous loop.

For the moment, the Enemy doesn’t seek out the player and attack when it’s within a preset range.

 

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : conclusion done

 

Done! i created the project Csharp First FPS artificial intelligence to enemy patrol on windows 11 version 26100.

The enemy can walk around the arena, patrol between coordinates to seek for the player, and choose himself his path to ovoid the turrets.

With only four waypoints, the generative AI generates the path and decides where the enemy goes for a walk.

Windows 11 26100 Csharp FirstFPS artificial intelligence to enemy patrol gif

Windows 11 v26100 Csharp First FPS; Artificial intelligence to enemy patrol : need help ? 

 

Need help with Windows 11 or C# with Unity?

Fill this form or send an email on loic @consultingit.fr or This email address is being protected from spambots. You need JavaScript enabled to view it. and i will be happy to help you :)